Vue组件内部实现一个双向数据绑定

3次阅读

共计 439 个字符,预计需要花费 2 分钟才能阅读完成。

来源于:阿贤博客
思路:父组件通过 props 传值给子组件,子组件通过 $emit 来通知父组件修改相应的 props 值,具体实现如下:
import Vue from ‘vue’
const component = {
props: [‘value’],
template: `
<div>
<input type=”text” @input=”handleInput” :value=”value”>
</div>
`,
data () {
return{}
},
methods: {
handleInput (e) {
this.$emit(‘input’, e.target.value)
}
}
}

new Vue({
components: {
CompOne: component
},
el: ‘#root’,
template: `
<div>
<comp-one :value1=”value” @input=”value = arguments[0]”></comp-one>
</div>
`,
data () {
return{
value: ‘123’
}
}
})
来源于:阿贤博客

正文完
 0