v-model(Vue3)

v-model 是 Vue 的一个语法糖。在 Vue3 中的玩法就更多了

7-1 单个v-model绑定

<template>
  <Child v-model="message" />
</template>
<script setup>
  import Child from './child.vue';
  const message = ref('父传给子');
</script>
子组件:
<template>
  <div>
    <button @click="handleClick">修改model</button>
    {{ modelValue }}
  </div>
</template>
<script setup>
  // 接收
  defineProps([
    'modelValue', // 接收父组件使用 v-model 传进来的值,必须用 modelValue 这个名字来接收
  ]);
  const emit = defineEmits(['update:modelValue']); // 必须用 update:modelValue 这个名字来通知父组件修改值
  function handleClick() {
    // 参数1:通知父组件修改值的方法名
    // 参数2:要修改的值
    emit('update:modelValue', '子改变值');
  }
</script>
 

7-2 多个v-model绑定

<template>
  <Child v-model:msg1="message1" v-model:msg2="message2" />
</template>
<script setup>
  import Child from './child.vue';
  const message1 = ref('水果1');
  const message2 = ref('水果2');
</script>
子组件:
<template>
  <div>
    <div><button @click="changeMsg1">修改msg1</button> {{ msg1 }}</div>
    <div><button @click="changeMsg2">修改msg2</button> {{ msg2 }}</div>
  </div>
</template>
<script setup>
  // 接收
  defineProps({
    msg1: String,
    msg2: String,
  });
  const emit = defineEmits(['update:msg1', 'update:msg2']);
  function changeMsg1() {
    emit('update:msg1', '蔬菜1');
  }
  function changeMsg2() {
    emit('update:msg2', '蔬菜2');
  }
</script>

7-3 v-model修饰符

v-model 还能通过 . 的方式传入修饰。v-model 有内置修饰符——.trim、.number 和 .lazy。但是,在某些情况下,你可能还需要添加自己的自定义修饰符。

<template>
  <Child v-model.uppercasefn="message" />
</template>
<script setup>
  import Child from './child.vue';
  const message = ref('水果');
</script>
子组件:
<template>
  <div>
    <div>{{ modelValue }}</div>
  </div>
</template>
<script setup>
  const props = defineProps(['modelValue', 'modelModifiers']);
  const emit = defineEmits(['update:modelValue']);
  onMounted(() => {
    console.log(props.modelModifiers, '自定义v-model 修饰符');
    // 判断有没有uppercasefn修饰符,有的话就执行 下面得方法 方法
    if (props.modelModifiers.uppercasefn) {
      emit('update:modelValue', '蔬菜');
    }
  });
</script>
 

参考:

vue3的组件通信&v-model使用实例详解_vue.js_脚本之家

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值