如何在自定义组件内使用`v-model`

默认情况下,一个组件上的 v-model 会把 value 用作 prop 且把 input 用作 event,自定义组件内使用v-model可以定制 prop 和 event

<!-- child -->
<div class="child">
  <p>{
    
    {
    
     give }}</p>
  <button @click="returnBackFn">回应</button>
</div>

export default {
    
    
  props: {
    
    
    give: String
  },
  model: {
    
    
    prop: 'give',
    event: 'returnBack'
  },
  methods: {
    
    
    returnBackFn() {
    
    
      this.$emit('returnBack', '还你200块');
    }
  }
}
<!-- parent -->
<div class="parent">
  <p>{
    
    {
    
     sthGiveChild }}</p>
  <Child v-model="sthGiveChild" />
</div>

export default {
    
    
  data() {
    
    
    return {
    
    
      sthGiveChild: '给你100块'
    }
  }
}

<!-- 相当于 -->
<Child :give="sthGiveChild" @returnBack="val => sthGiveChild = val" />

猜你喜欢

转载自blog.csdn.net/weixin_44257930/article/details/108829698
今日推荐