学习vue3 七 v-model用于组件通信,自定义指令,自定义hooks

v-model

在vue3中v-model是破环性更新

v-model其实是一个语法糖,通过props和emit组成

子组件要修改父组件的值

  • prop:value -> modelValue
  • 事件:input -> update:modelValue
  • v-bind 的 .sync 修饰符和组件的 model 选项已移除

v-model的更多用法

  • 新增 支持多个v-model
  • 新增 支持自定义 修饰符 Modifiers

单个v-model 

案例:

父组件

<script setup lang="ts">
// 通过v-model来实现父子组件之间的双向绑定
import A from './components/A.vue'
import {ref} from "vue";
const flag = ref(true)

</script>

<template>
  <div class="switch">
    {
  {flag}}
    <button @click="flag = !flag">切换</button>
  </div>
  <transition
    enter-active-class="animate__animated animate__backInDown"
    leave-active-class="animate__animated animate__backOutDown">
    <A v-model="flag"></A>
  </transition>
</template>

<style scoped>
.switch {
  width: 200px;
  margin: 5px auto;
}
</style>

子组件

<script setup lang="ts">
defineProps<{
  modelValue:boolean
}>()
const emit = defineEmits<{
  (e:'update:modelValue', value: boolean): void
}>()
function submit() {
  emit('update:modelValue', false)
}
</script>

<template>
  <div class="container" v-if="modelValue">
    <div>
      <span>请输入:</span>
      <input type="text">
    </div>
    <button @click="submit">提交</button>
  </div>
</template>

<style scoped>
.container {
  width: 500px;
  height: 500px;
  background-color: #ccc;
  border: 1px solid grey;
  margin: 0 auto;
}
.header {
  height: 50px;
  background-color: #eee;
  border: 1px solid grey;
}
.body {
  height: 400px;
  background-color: #ddd;
  border: 1px solid grey;
}
.footer {
  height: 50px;
  background-color: #eee;
  border: 1px solid grey;
}
</style>

也可以给一个组件绑定多个v-model

案例:

父组件

<A v-model="
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值