v-model实现父子组件双向数据绑定

79 阅读1分钟

需求:手写一个多选框,不同的父组件给予不同的初始值

1.解决子组件中v-model不能绑定prop值的问题(通过computed)

<template>
  <div>
   <!--父组件-->
    <child :title="title" @changeTitle="changeTitle"></child>
  </div>
</template>

<script>
import Child from "./child.vue";
export default {
  components: { Child },
  name: "Parent",
  data() {
    return {
      title: "你好啊",
    };
  },
  methods: {
    changeTitle(val) {
      this.tilte = val;
    },
  },
};
</script>


<template>
  <div>
    <!--子组件-->
    <input type="text" v-model="titleMo" />
  </div>
</template>
<script>
export default {
  name: "HelloWorld",
  props: {
    title: String,
  },
  computed: {
    titleMo: {
      get() {
        return this.title;
      },
      set(val, oval) {
        if (val !== oval) {
          this.$emit("changeTitle", val);
        }
      },
    },
  },
  data() {
    return {};
  },
};
</script>

2.v-model="city" 就等价于 :isCity="city" 加上 @changeCity="city = $event.target.isCity"

<template>
  <div>
    <child v-model="city"></child>
  </div>
</template>

<script>
import Child from "./child.vue";
export default {
  components: { Child },
  name: "Parent",
  data() {
    return {
      city: ["上海", "北京"],
    };
  },
  methods: {},
};
</script>

<template>
  <div>
    <el-checkbox-group
      v-model="checkedCities">
      <el-checkbox v-for="city in cityOptions" :label="city" :key="city">{{
        city
      }}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>
<script>
export default {
  name: "HelloWorld",
  model: {
    prop: "isCity",
    event: "changeCity",
  },
  props: {
    isCity: Array,
  },
  computed: {
    checkedCities: {
      get() {
        return this.isCity;
      },
      set(val, oval) {
        this.$emit("changeCity", val);
      },
    },
  },
  data() {
    return {
      cityOptions: ["上海", "北京", "广州", "深圳"],
    };
  },
};
</script>


<style scoped>
</style>
Child