在vue3中我们难免会进行组件的使用,这时我们就要使用到父子传值
1、父组件给子组件进行传值
<template>
<button @click='change'>按钮</button>
//父组件
<DetailDialog v-model="createDialog" :detailsList="detailsList" />
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import DetailDialog from './detailDialog.vue'
const createDialog = ref<boolean>(false)
const detailsList = ref([]) as string[]
const change = () => {
createDialog.value = true
detailsList.value = [{name:'张三',age:'18'},{name:'李四',age:'25'}]
}
</script>
<style lang="scss" scoped>
</style>
vue3通过defineProps存储父组件传递过来的值
<template>
{{props.modelValue}} --- {{detailsList}}
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
const props = defineProps({
modelValue: {
type: Boolean,
default: false
},
detailsList: {
type: Object,
default: () => {
return {}
}
}
})
</script>
<style lang="scss" scoped>
</style>
2、子组件给父组件进行传值或者修改父组件的值如何实现
vue3中我们需要借助defineEmits来实现
<template>
//父组件
<button @click='change'>按钮</button>
{{createDialog}} --- {{sonValue}}
<DetailDialog v-model="createDialog" @son="son" />
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import DetailDialog from './detailDialog.vue'
const createDialog = ref<boolean>(false)
const detailsList = ref([]) as string[]
const sonValue = ref<string>('')
const change = () => {
createDialog.value = true
}
const son = (val) => {
console.log(val,'子传递的值')
sonValue.value = val
}
</script>
<style lang="scss" scoped>
</style>
<template>
//子组件
<button @click='close'>修改父组件传递的状态</button>
<button @click='son'>给父组件传值</button>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
const props = defineProps({
modelValue: {
type: Boolean,
default: false
}
})
const emit = defineEmits(['update:modelValue','son'])
const close = () => {
emit('update:modelValue', !props.modelValue)
}
const son = () => {
emit('son', '这是传递的值')
}
</script>
<style lang="scss" scoped>
</style>