Vue3使用v-model实现父子组件传值的两种方式
第一种方式:普通写法父组件:Father.vue<template><h1>父组件</h1><el-button @click="showDialog">点击展示弹框</el-button><Dialog v-model:dialogVisible="dialogVisible" /></template><
·
第一种方式:普通写法
父组件:Father.vue
<template>
<h1>父组件</h1>
<el-button @click="showDialog">点击展示弹框</el-button>
<Dialog v-model:dialogVisible="dialogVisible" />
</template>
<script>
import { Dialog } from '@components/Dialog.vue'
export default {
setup() {
const dialogVisible = ref(false);
function showDialog(){
dialogVisible.value = true
};
return {
dialogVisible,
showDialog
}
},
}
</script>
子组件:Child.vue
<template>
<el-dialog v-model="dialogVisible" title="我是一个弹框">
<p>我是弹框的内容</p>
<el-button @click="confirm">关闭弹框</el-button>
</el-dialog>
</template>
<script>
export default {
props: {
dialogVisible: {
type: Boolean,
required: true,
},
},
setup(props, { emit }) {
function confirm() {
emit("update:dialogVisible", false);
}
return {
confirm,
};
},
};
</script>
第二种写法:组合式API
父组件:Father.vue
<template>
<h1>父组件</h1>
<el-button @click="showDialog">点击展示弹框</el-button>
<Dialog v-model:dialogVisible="dialogVisible" />
</template>
<script setup>
import { Dialog } from "@components/Dialog.vue";
const dialogVisible = ref(false);
const showDialog = () => {
dialogVisible.value = true;
};
</script>
子组件:Child.vue
<template>
<el-dialog v-model="dialogVisible" title="我是一个弹框">
<p>我是弹框的内容</p>
<el-button @click="confirm">关闭弹框</el-button>
</el-dialog>
</template>
<script setup>
const props = defineProps({
dialogVisible:{
type:Boolean,
required:true
}
});
const emit = defineEmits(["update:dialogVisible"]);
const confirm = ()=>{
emit('update:dialogVisible',false)
};
</script>
更多推荐
已为社区贡献6条内容
所有评论(0)