Vue: 在自定义组件上使用 v-model

定义一个用于评分的 RatingControl.vue 组件,用户可以从 poor, averagegreat 3项中选择一项,如下所示:
在这里插入图片描述
如果在RatingControl.vue上定义属性'modelValue',并发出名称为'update:modelValue'的事件,根组件App.vue同样可以使用 v-model 实现数据与事件的双重绑定。
RatingControl.vue:

<template>
    <ul>
        <li :class="{active: modelValue === 'poor'}"><button type="button" @click="activate('poor')">Poor</button></li>
        <li :class="{active: modelValue === 'average'}"><button type="button" @click="activate('average')">Average</button></li>
        <li :class="{active: modelValue === 'great'}"><button type="button" @click="activate('great')">Great</button></li>
    </ul>
</template>

<script>
export default {
    props: ['modelValue'],
    emits: ['update:modelValue'],
    methods: {
        activate(option) {
            this.$emit('update:modelValue', option);
        }
    }
}
</script>

App.vue:

<form>
    <!-- ............. -->
    <div class="form-control">
      <rating-control v-model="rating"></rating-control>
    </div>
    <div class="form-control"> 
      <input type="checkbox" id="confirm-terms" name="confirm-terms" v-model="confirm"/>
      <label for="confirm-terms">Agree to terms of use?</label>
    </div>
    <div>
      <button>Save Data</button>
    </div>
  </form>

使用这种方法,可以如同使用 input 元素一样使用自定义组件。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值