vue2及vue3父子组件v-model双向数据绑定

1,002 阅读1分钟

vue2及vue3父子组件v-model双向数据绑定

vue2

使用.sync修饰符实现

  • 子组件
<template>
  <div>
    <div>{{ num }}</div>
    <button @click="changeNum">改变父组件值</button>
  </div>
</template>

<script>
export default {
  name: "Child",
  props: {
    num: Number,
  },
  methods: {
    changeNum() {
      this.$emit("update:num", this.num - 1000);
    },
  },
};
</script>
  • 父组件
<template>
  <div>
    <div>{{ num }}</div>
    <hr />
    <Child :num.sync="num" />
  </div>
</template>

<script>
import Child from "./components/child.vue";

export default {
  name: "App",
  components: {
    Child,
  },
  data() {
    return {
      num: 10000,
    };
  },
};
</script>

vue3

方式一

组件上的 v-model 默认使用 modelValue 作为 prop 和 update:modelValue 作为事件

  • 子组件
<script setup>
const props = defineProps({
  modelValue: Number,
});
const emit = defineEmits();
function changeNum() {
    emit("update:modelValue", props.modelValue - 1000);
}
</script>

<template>
  <h1>{{ num }}</h1>
  <button @click="changeNum">改变num</button>
</template>
  • 父组件
<script setup>
import { ref } from "vue";
import Child from "./components/child.vue";

const num = ref(10000);
</script>

<template>
  <div>{{ num }}</div>
  <hr />
  <Child v-model="num" />
</template>

方式二

  • 子组件
<script setup>
const props = defineProps({
  num: Number,
});
const emit = defineEmits(["update:num"]);

function changeNum() {
  emit("update:num", props.num - 1000);
}
</script>

<template>
  <h1>{{ nums }}</h1>
  <button @click="changeNum">改变num</button>
</template>
  • 父组件
<script setup>
import { ref } from "vue";
import Child from "./components/child.vue";

const num = ref(10000);
</script>

<template>
  <div>{{ num }}</div>
  <hr />
  <Child v-model:num="num" />
</template>