vue3setup语法中组件使用v-model

309 阅读1分钟

描述

父子之间的双向绑定使用defineModel更简洁。以前要实现数据双向绑定需要给子组件定义一个modelValue属性,并且在子组件内要更新modelValue值时需要emit出去一个update:modelValue事件,将新的值作为第二个字段传出去。下面我描述使用defineModel如何进行组件间的双向绑定

基本使用

父子组件之间数据的双向绑定,父组件输入子组件数据也跟着变化,子组件更新父组件也跟着更新,举例如下:

父组件代码

<script setup>
import { ref } from "vue";
const parentInputValue = ref("")

</script>

<template>
  <div>
    <div>
      父组件的输入框<input type="text" v-model="parentInputValue">
      <children3 v-model="parentInputValue"></children3>
    </div>
  </div>
</template>

<style lang="less" scoped>

</style>

子组件代码

使用defineModel直接可以拿到父组件传递过来绑定的值,子组件改变,父组件也会跟着改变,父组件改变也会改变传给子组件的数据

<script setup>

const model = defineModel();

</script>

<template>
  <div class="children3">
    子组件的输入框<input type="text" v-model="model">
  </div>
</template>

<style lang="less" scoped>
.children3{
    width: 200px;
    height: 200px;
    background-color: yellow;
    font-size: 12px;
}
</style>

组件使用多个v-model

可以通过指定参数的方式进行一个组件绑定多个数据的情况。

父组件代码

<script setup>
import { ref, reactive, provide } from "vue";
import Children3 from "./Children3.vue"const router = useRouter();

const numberData = ref(100)
</script>

<template>
  <div>
    <div>
      父组件的输入框<input type="text" v-model="parentInputValue">
      <children3 v-model="parentInputValue" v-model:modelName="numberData"></children3>
    </div>
  </div>
</template>

<style lang="less" scoped>
</style>

子组件代码

通过modelName参数方式使用多个v-model

<script setup>

const model = defineModel();
const model2 = defineModel('modelName');
const handleSubNumber = () => {
  model2.value--;
}

</script>

<template>
  <div class="children3">
    子组件的输入框<input type="text" v-model="model">
    另一个数据:{{model2}}
    <button @click="handleSubNumber">递减父组件按钮</button>
  </div>
</template>

<style lang="less" scoped>
.children3{
    width: 200px;
    height: 200px;
    background-color: yellow;
    font-size: 12px;
}
</style>