转载一文章
https://blog.csdn.net/weixin_43845137/article/details/123534181
1,父组件
<template>
<div>
<Child
v-model:custom="message"
@update:custom="updateCustom"
></Child>
<h1>父急?{{ message }}</h1>
</div>
</template>
<script lang="ts" setup>
import { ref, unref } from 'vue';
import Child from './testCom.vue';
let message = ref("Hello World Vue3");
const updateCustom = (val) => {
message.value = val
}
</script>
1,子组件
<template>
<div> <input v-model="propsMessage" type="text"> </div>
</template>
<script setup lang="ts">
import { ref, computed } from "vue";
let props = defineProps({
custom: String
})
const emmits = defineEmits(['update:modelValue', 'update:custom'])
const propsMessage = computed({
get: () => {
return props.custom
},
set: (val) => {
console.log("sssssss")
emmits('update:custom', val)
}
})
</script>
<style scoped>
.footer-wrap {
display: flex;
justify-content: flex-end;
}
</style>
2,实例
//父组件
<template>
<div>
<Child v-model="showAdress" ></Child>
<button @click="open">展示</button>
</div>
</template>
<script lang="ts" setup>
import { ref, unref } from 'vue';
import Child from './testCom.vue';
const showAdress = ref(false)
function open() {
showAdress.value = true
}
</script>
//子组件
<script setup>
// props
const props = defineProps({
'model-value': {
type: Boolean,
required: false,
default: false
}
});
const emit = defineEmits(['update:model-value']);
function close() {
emit('update:model-value', false)
}
</script>
<template>
<div v-if="modelValue">
<div class="">我是子组件</div>
<button @click="close">关闭</button>
</div>
</template>
代码块
**************************************************************************
3.支持多个
//父组件
<template>
<div>
<Child v-model="flag" v-model:title="title" ></Child>
<button @click="flag = !flag">展示</button>
</div>
</template>
<script lang="ts" setup>
import { ref, unref } from 'vue';
import Child from './testCom.vue';
let flag = ref<Boolean>(true)
let title = ref<String>('我是小渣亮')
const showAdress = ref(false)
function open() {
showAdress.value = true
}
</script>
//子组件
<template>
<div v-if="modelValue" class="dialog">
<div class="dialog-header">
<span>标题 - {{ title }}</span>
<button @click="close">关闭</button>
</div>
<div class="dialog-main">
<button @click="changTitle">修改 标题</button>
{{ modelValue }}
</div>
</div>
</template>
<script setup lang="ts">
type Props = {
modelValue: Boolean
title: String
}
defineProps<Props>()
const emit = defineEmits(['update:modelValue', 'update:title'])
const close = () => {
emit('update:modelValue', false)
}
const changTitle = () => {
emit('update:title', '我就是狗啊')
}
</script>
<script lang="ts">
export default {
name: 'Dialog',
}
</script>
网友评论