Two Way Binding in Vue3

发表于 2024-01-26
更新于 365 日前 语言暂不支持 许可证 CC BY-NC-SA 4.0 vuetypescript

A simple two way binding example in vue3.

Child.vue:

<script lang="ts" setup>
const name = defineModel<string>("name");
const age = defineModel<number>("age");

const updateAgeInChild = () => {
  ++age.value;
};
</script>

<template>
  <h1>Child:</h1>
  <p>name: {{ name }}</p>
  <p>age: {{ age }}</p>
  <input type="text" v-model="name" />
  <button @click="updateAgeInChild()">Add age in Child</button>
</template>

Parent.vue:

<script lang="ts" setup>
import { ref } from "vue";
import Child from "./Child.vue";

const name = ref("BlockLune");
const age = ref(0);

const updateAgeInParent = () => {
  ++age.value;
};
</script>

<template>
  <Child v-model:name="name" v-model:age="age" />
  <h1>Parent:</h1>
  <p>name: {{ name }}</p>
  <p>age: {{ age }}</p>
  <input type="text" v-model="name" />
  <button @click="updateAgeInParent">Add in Parent</button>
</template>

App.vue:

<script setup>
import Parent from "./Parent.vue";
</script>

<template>
  <Parent />
</template>

Learn more at Component v-model | Vue.js. Note the Under the Hood part.