[轉] vue 自定義組件使用v-model


 

<input v-model="something">

v-model指令其實是下面的語法糖包裝而成:

<input
  :value="something"
  @:input="something = $event.target.value">

在一個組件上使用 v-model 時,會簡化為:

<custom-input
  :value="something"
  @input="value => { something = value }">
</custom-input>

因此,對於一個帶有 v-model 的組件,它應該如下:

  • 接收一個 value prop
  • 觸發 input 事件,並傳入新值

利用 $emit 觸發 input 事件:

this.$emit('input', value);

組件1:

復制代碼
Vue.component('my-component', {
  template: `<div>
  <input type="text" :value="currentValue" @input="handleInput"/>
  </div>`,
  computed:{
    currentValue:function () {
      return this.value
    }
  },
  props: ['value'], //接收一個 value prop
  methods: {
    handleInput(event) {
      var value = event.target.value;
      this.$emit('input', value); //觸發 input 事件,並傳入新值
    }
  }
});    
復制代碼
上面是將prop屬性綁定到data里,以便修改 prop 數據(Vue不允許直接修改prop屬性的值)#查看原理#

組件2:

復制代碼
Vue.component("my-counter", {
  template: `<div>
  <h1>{{value}}</h1>
  <button @click="plus">+</button>
  <button @click="minu">-</button>
  </div>`,
  props: {
    value: Number //接收一個 value prop
  },
  data: function() {
    return {
      val: this.value
    }
  },
  methods: {
    plus() {
      this.val = this.val + 1
      this.$emit('input', this.val) //觸發 input 事件,並傳入新值
    },
    minu() {
      if(this.val>0){
        this.val = this.val-1
        this.$emit('input', this.val) //觸發 input 事件,並傳入新值
      }
    }
  }
});
復制代碼

https://www.jianshu.com/p/3dbbbc7a259c


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM