vue3里面v-model 如何给子组件传递单个或者多个参数
在components目录下新建一个Child.vue子组件
单个参数传递的情况
<script setup>
import { ref } from 'vue'
//接收父组件传来的值
const props = defineProps({
modelValue: String
})
//更改父组件的值
const emit = defineEmits(['update:modelValue'])
const updateValue = () => {
emit('update:modelValue', '王五')
}
</script>
<template>
<h1>子组件参数:{{ modelValue }}</h1>
<button @click="updateValue">更改父组件值</button>
</template>
父组件定义如下
<script setup>
import { ref } from 'vue'
import Child from './components/Child.vue'
const param1 = ref('张三')
</script>
<template>
<div>
<div>父组件:{{ param1 }}</div>
<Child v-model="param1" />
</div>
</template>
多个参数传递的写法如下
<script setup>
import { ref } from 'vue'
//通过defineProps接收多个参数
const props = defineProps({
lastName: String,
firstName: String
})
const emit = defineEmits(['update:lastName', 'update:firstName'])
const updateLastName = () => {
emit('update:lastName', '11111')
}
const updateFirstName = () => {
emit('update:firstName', '2222')
}
</script>
<template>
<div>
<h4>lastName:{{ lastName }}</h4>
<h4>firstName:{{ firstName }}</h4>
</div>
<div>
<button @click="updateLastName">更改lastName</button>
<button @click="updateFirstName">更改firstName</button>
</div>
</template>
父组件改写为
<script setup>
import { ref } from 'vue'
import Child from './components/Child.vue'
//多个参数值
const lastName = ref('王五')
const firstName = ref('王刘')
</script>
<template>
<div>
<div>父组件:{{ lastName }}---{{ firstName }}</div>
<Child v-model:lastName="lastName" v-model:firstName="firstName" />
</div>
</template>