vue2.0中的render函数怎么实现双向数据绑定

2025-05-09 01:52:20
推荐回答(1个)
回答1:

一,先创建一个叫eventbus的vue对象,什么配置都不需要,就只是拿来做一个event bus而已。第二,因为组件的props不允许更改,所以呢要用另一个变量来作为中转,也就是呢,组件不能用functional为true了。然后组件里头定义了个currentValue,绑定在props定义的value,这样:data: function() { return { currentValue: this.value }}第三,组件里头添加watch属性,监听value和currentValue的变化,这样:watch: { value: function(newValue, oldValue) { this.currentValue = newValue; //这里有点诡异,最后说document.getElementById(inputId).value=this.currentValue; }, currentValue: function(newValue){ eventbus.$emit('model-change', this.modelName, newValue); }}这里,还需要在props里头加一个modelName的字段给组件标签绑定,后面有用呢。。第四,在input标签里头要绑个input的事件,这样:var that = this;createElement('input', { //... 'on': { 'input': function(event){ that.currentValue = event.target.value; } }})第五,绑定这个标签的Vue对象里头,要加个created的钩子,绑个model-change的事件,这样:created: function() { var that = this; eventbus.$on('model-change', function(modelName, modelValue) { Vue.set(that.$data, modelName, modelValue); });}最终,标签变成了这样:user.name的默认值是Mary,渲染出来的时候也是显示Mary,敲键盘改值改成xxx,控制台里头看一下,user.name也变成了xxx了,在控制台里头将user.name改成abc,框里头也变成abc了。终于可以双向绑定了。