32.Vue 自定義組件使用v-model

在Vue2中自定義組件可以使用v-model指令,來實現雙向綁定,前提條件:
1、接收一個value屬性
2、在有新的value時觸發intput事件

案例

index.vue

<template>
  <div>
      total值:{{total}}  <br/> <br/>
      <testVue v-model="total"></testVue>
  </div>
</template>
<script>
import testVue from './testVue'
export default {
  data(){
    return {
      total: 0    
    }
  },
  components: {
     testVue 
  }
}
</script>

testVue.vue

<template>
<div>
  傳入的值: {{value}} <br/>
  <button @click="changeVal">改變值</button>
</div>
</template>
<script>
export default {
  data(){
    return {
      counter: 0
    }
  },
  propos: {
    // 接收外部通過v-model傳入的只,必須是value
    value: {}
  },
  methods: {
    changeVal(){
      this.$emit('input', this.counter++)
    }
  }
}
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章