V-model组件间传值

1、v-model特性

  1. 可以在原生元素上使用以实现数据的双向绑定
  2. 在组件上使用v-model会等价展开以下
    :modelValue="text"

    @update:modelValue="newValue=>text=newValue"
    // 表明可以拿到修改的新值modelValue,改不改text的值是可选项

  3. 组件内部接收的话需要

    const props = defineProps(['modelValue'])

    const emit = defineEmits(['update:modelValue'])

  4. 可以通过v-bind="$attrs"透传,直到有人props接住

2、示例

1、父与子之间传递
  1. 父组件
    1. 给 VModelChild绑定message,采用等价展开的方式,并对传回来的新值进行修改再赋值
  2. 子组件
    1. 通过props接收modelValue,想要修改,但是不能直接修改props中的值,通过computed计算属性,发射修改的值,交给上层

<!-- 父组件 -->
<script setup>
import VModelChild from './VModelChild.vue';
import VModelmid from './VModelmid.vue';
import { ref, } from 'vue'
const message = ref('')

</script>
<template>
    <h3>VModelParent</h3>
    <div>信息为 : {{ message }}</div>
    <VModelChild
    :modelValue="message"
    @update:modelValue="newValue => message = newValue+' ok ok '" />

</template>
<!-- 子 -->
<script setup>
import {computed} from 'vue'
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])

const updateValue = computed({
    get:()=>props.modelValue,
    set:value=>emit('update:modelValue',value)
})

function editValue (){
    updateValue.value = 'hello World'
}

</script>
<template>
    <h3>VModelChild</h3>
    <input type="text" :placeholder="modelValue">
    <button @click="editValue">发送信息</button>
</template>
2、隔代传递

将父组件中绑定v-model的组件换为VModelMid

  1. 中间组件通过v-bind="$attrs"将v-model传递给VModelChild组件
  2. 并监听update:modelValue事件,接收传的值并展示
  3. 而Child中展示的信息为修改后的是由于读取的modelValue
<!-- 中间组件 -->
<script setup>
import VModelChild from './VModelChild.vue';
import { ref } from 'vue'
const message  = ref('')
</script>
<template>
    <h3>VModelmid</h3>
    <p>信息为:{{ message }}</p>
    <div>
        <VModelChild @update:model-value="newValue=>message=newValue" v-bind="$attrs" />
    </div>
</template>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值