Vue v-model自定义组件

338 阅读1分钟

在项目中自定义组件使用 v-model 实现双向数据绑定。

<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>

在父布局中使用

<cus-radio v-model="value" :values="values" />