【vue】使用.sync 实现数据的双向绑定

在 vue 中想要在父子组件中实现数据的双向绑定(子组件能感知父组件的值的修改,父组件能感知子组件的值的修改)有三种方式:

  • v-model
  • 动态绑定数据+显示事件监听
  • .sync
    三种方式各有千秋,v-model 只能绑定一个对象,动态绑定数据+显示事件监听略显麻烦,.sync 相对方便简单一点。(个人直观感受,详细差异有待挖掘)
.sync 的使用

子组件 mySelect.vue 代码:

<template>
  <el-select v-model="newFood" placeholder="请选择">
    <el-option v-for="item in options" :key="item.value" :value="item.value">
    </el-option>
  </el-select>
</template>

<script>
  export default {
    props: {
      food: {
        type: String,
        default: "",
      },
    },
    data() {
      return {
        options: [
          {
            value: "黄金糕",
          },
          {
            value: "双皮奶",
          },
        ],
      };
    },
    computed: {
      newFood: {
        get() {
          return this.food;
        },
        set(newValue) {
          this.$emit("update:food", newValue);
        },
      },
    },
  };
</script>

父组件代码:

<template>
  <div id="example">
    <my-select :food.sync="food"></my-select>
    <span>我选择的食物是:{{ food }}</span>
    <div>
      <el-button @click="handleClick" type="primary">我要黄金糕</el-button>
    </div>
  </div>
</template>
<script>
  import MySelect from "./mySelect.vue";
  export default {
    components: { MySelect },
    data() {
      return {
        food: "",
      };
    },
    methods: {
      handleClick() {
        this.food = "黄金糕";
      },
    },
  };
</script>

运行结果:
父组件的 food 属性和子组 mySelect 的选择框内容是联动的,相互影响的。
子组件影响父组件(通过子组件 mySelect 选择食物)运行结果:
在这里插入图片描述
父影响子组件(点击“我要黄金糕”)运行结果:
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐