「这是我参与2022首次更文挑战的第19天,活动详情查看:2022首次更文挑战」
涉及的知识点
- @Model('change')详解,包括具体参数的详解和v-model的区别
- @Emit('change')详解,包括具体参数的详解,什么情况下用@Emit('change'),什么情况下用this.$emit
- @Prop() answer!: string;
- @Watch 的详解,包括具体参数详解
- @Prop() time?: number; ?和 !的区别?
@Model
平时开发中使用v-model='value'用在input上,会被编译成value='value' @input='(ev) => {value = ev.target.value}' ,这种写法用在type='text'是没问题的,如果type='select/checkbox'时,有两个问题
- checkbox是用checked判断是否被选中、value是它的一个普通属性。如果父组件同时传了v-model和value如下,打印的是val。
- checkbox没有input事件,怎样双向绑定?(它有change事件)
<Model v-model="val" value='321321312' />
// Model组件
<input type="checkbox" :checked="inputValue" :value="value" v-on:change="$emit('aaa', $event.target.checked)" />
export default {
props: ["value"],
created() {
console.log(this.value) // val
},
};
我们怎么获取到‘321321312’呢?
- prop: "inputValue", 解决第一个问题
- event: "aaa", 解决第二个问题,aaa是一个别名,如果设置,直接用v-on:change="event.target.checked)"也可以。
export default {
props: ["inputValue", "value"],
model: {
prop: "inputValue", // 解决第一个问题,默认值value
event: "aaa", // 解决第二个问题,默认值input
},
// @Model('change') value!: string;
created() {
console.log(this.value) // 321321312
console.log(this.inputValue) // val
},
};
@Emit('eventName')
平时使用emit
this.$emit('eventName', param)
ts中也可以:调用时会比较方便
@Emit('eventName')
eventNameProxy(param) {
return param;
}
close() {
this.eventNameProxy(param);
}
作用:提前注册一下eventName,生成一个代理函数,下次可以直接调用代理函数,实现原理:
// 订阅
mounted() {
this.$on('eventName', (param) => {
alert(data)
})
},
methods: {
eventNameProxy(val) {
// 发布
this.$emit('eventName', val)
}
}
@Prop() answer!: string;@Prop() answer?: string;感叹号和问号什么意思?
- !:属性的类型后面需要加上undefined 类型;或者在属性名后面加上!,表示非null 和 非undefined的断言,否则编译器会给出错误提示;使null和undefined类型可以赋值给其他类型并通过编译;
- ?:表示可选参数;
@Watch
@Watch('inputValue', { deep: true })
valueChange(newValue: string, oldValue: string) {
console.log(newValue, oldValue)
}
// 等于
watch: {
inputValue: {
handler: (newValue, oldValue) {
console.log(newValue, oldValue)
},
deep: true
}
}