世事洞明皆学问,人情练达即文章。(《红楼梦》)
子组件使用v-model
父组件
// father.vue
<template>
<div class="father">{{ fatherRef }}</div>
<Child :fatherRef="fatherRef" @changeVal="changeVal"></Child>
</template>
<script setup lang="ts">
import { ref } from "vue";
import Child from "./Child.vue";
const fatherRef = ref("1");
function changeVal(val: string) {
fatherRef.value = val;
}
</script>
<style lang="scss" scoped>
.father {
margin-top: 40px;
margin-bottom: 40px;
}
</style>
通过computed函数,set函数触发emit方法。get获取父组件传过来的fatherRef
// child.vue
<template>
<input v-model="inputVal"/>
</template>
<script lang="ts" setup>
const props = defineProps<{fatherRef: String}>()
const emits = deineEmits(['changeVal'])
const inputVal = computed({
set:(val:String) => {
emits('changeVal',val)
},
get: () => {
return props.fatherRef
}
})
</script>
可以从父组件传递值和改变值的方法,然后子组件也可以使用v-model
例子中父组件传递 modelValue和update:modelValue方法 父组件
<template>
<Child :modelValue="searchText" @update:modelValue="changeVal"> </Child>
</template>
<script setup lang="ts">
import { ref } from "vue";
import Child from "./Child.vue";
const searchText = ref(1);
function changeVal(val: number) {
searchText.value = val;
}
</script>
<style lang="scss" scoped>
.father {
margin-top: 40px;
margin-bottom: 40px;
}
.btn {
font-size: 20px;
color: red;
}
</style>
子组件
<template>
<input v-model="modelValue" />
</template>
<script setup lang="ts">
import { computed, useAttrs, useSlots } from "vue";
const props = defineProps<{
modelValue: number;
}>();
// const emits = defineEmits(["changeVal"]);
</script>
<style lang="scss" scoped>
.child {
}
</style>