在项目中自定义组件使用 v-model 实现双向数据绑定。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
<template> ... <el-radio-group v-model="curValue" @change="valueChanged"> <el-radio v-for="(item, index) in values" :label="item">{{item}}</el-radio> </el-radio-group> ... </template>
<script> export default { name: 'cus-radio', data() { return { curValue: this.value } }, props: { value: { type: String, default: '' }, values: { type: Array, default: function () { return [] } } }, mounted() { // 在 Vue 中不能直接修改 props 里面的内容 // 需要在 data() 或 computed() 中定义一个与 value 相关联的值当做媒介 this.curValue = this.value }, methods: { valueChanged() { // 当 curValue 改变时,将新的值通过自定义的 input 事件抛出 this.$emit('input', this.curValue) } } } </script>
|
在父布局中使用
1
|
<cus-radio v-model="value" :values="values" />
|
近期评论