當前位置:編程學習大全網 - 源碼下載 - vue2.0中的render函數怎麽實現雙向數據綁定

vue2.0中的render函數怎麽實現雙向數據綁定

壹,先創建壹個叫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); });}最終,標簽變成了這樣:<my-component :value="user.name" model-name="user.name"></my-component>user.name的默認值是Mary,渲染出來的時候也是顯示Mary,敲鍵盤改值改成xxx,控制臺裏頭看壹下,user.name也變成了xxx了,在控制臺裏頭將user.name改成abc,框裏頭也變成abc了。終於可以雙向綁定了。

  • 上一篇:Ardurino有幾種編程語言。
  • 下一篇:BLDC電機是什麽?
  • copyright 2024編程學習大全網