背景
封装统一组件的时候需要在父子组件的过程中进行数据通信,双向绑定,简单记录使用方法。
插槽的使用
props: {
text: {
type: String,
default: ''
}
}
组件监听
watch: {
// 子组件监听到当前实例数据变化 同步到父组件内
content: {
handler() {
console.log('监听到数据变化')
// 采用 .sync 修饰时的同步方法
this.$emit('update:text', this.content)
// 采用 @ 事件通知时的方法
this.$emit("text", content)
}
},
// 监听到来自父组件的数据变化 同步到当前实例内
text: {
handler() {
this.content = this.text
},
}
},
使用.sync
对变量名修饰
- 父组件使用
<editor v-model="tipsForm.contentHtml" :text.sync="tipsForm.text" :min-height="192"/>
- 子组件使用
this.$emit("update:text", content)
使用 @
对变量变化做监控
- 父组件使用
<editor v-model="tipsForm.contentHtml" @text="handleTextChang" :min-height="192"/>
// 使用方法 handleTextChang 获取
handleTextChang(data){
// 数据内容
}
- 子组件使用
this.$emit("text", content)
Q.E.D.