vue3中 使用setup
子组件接收父组件传过来的值,并修改该值
父组件
<template>
<add-user v-model:dialogAddVisible="dialogAddVisible" />
</template>
<script setup>
import AddUser from './addUser.vue'
import { ref, watch } from 'vue'
//需要修改的参数
const dialogAddVisible = ref(false)
// watch 监听一下
watch(dialogAddVisible, (val, old) => {
dialogAddVisible.value = val
console.log(dialogAddVisible.value)
})
</script>
子组件
<template>
<div v-model='isDialogAddVisible'></div>
</template>
<script setup>
import { reactive, defineProps, defineEmits, watch, ref, toRefs } from 'vue' // 直接复制项目中的代码,有些是当前代码用不到的,请忽略……
const props = defineProps({
dialogAddVisible: {
type: Boolean
}
})
const refProps = toRefs(props)
const emits = defineEmits(['update:dialogAddVisible']) // 此处需写'update'
const isDialogAddVisible = ref(false)
watch(() => refProps.dialogAddVisible, (val, old) => {
isDialogAddVisible.value = val
})
watch(() => isDialogAddVisible, (val, old) => {
emits('update:dialogAddVisible', val) // 此处的update亦要写
})
</script>
参考:https://blog.csdn.net/xiao_cheng_/article/details/122617946