Vue组件信息传递
编辑
5
2024-09-30
1.父传子
App.vue
<script setup>
import Head from './components/child.vue'
const propsInit = {
name: 'xian',
age: undefined,
temp: 'temp'
}
</script>
<template>
<Child propsName="Name先" :propsAge='20' :="propsInit"></Child >
</template>
<style scoped></style>
child.vue
<script setup>
//简单数据
const props = defineProps(['propsName', 'propsAge'])
console.log(props.propsName);
//对象
const props = defineProps({
name: String,
age: {
type:Number,
default:30
},
temp: {
type:String,
default:"22022",
required:true
}
})
console.log(props);
</script>
<template>
</template>
<style scoped></style>
2.子传父
利用
defineEmits()
实现
App.vue
<script setup>
import {ref} from 'vue';
// 子传父
import child from './components/child.vue'
const name = ref('')
const age = ref(0)
const emitsGetData = (data) => {
name.value = data.name
age.value = data.age
}
const emitsAddAge=(data)=>{
age.value+=data
}
</script>
<template>
<div>name:{{name}},age:{{age}}</div>
<child @getData='emitsGetData' @addAge="emitsAddAge"></child>
</template>
<style scoped></style>
child.vue
<template>
<button @click="addAge">增加年龄</button>
</template>
<script setup>
const emits = defineEmits(['getData'])
emits('getData', {
name: 'lis',
age: 22
})
const addAge=() => {
emits('addAge', 10)
}
</script>
<style>
</style>
3.跨组件传递
利用
provide()
与inject()实现
App.vue
<script setup>
import {provide} from 'vue';
//跨组件传递
import interval from './components/interval.vue';
const userData={
name:'lisa',
age:23,
favor:'books'
}
//需导入provide
provide("provideUserData",userData)
</script>
<template>
<div>跨组件传递</div>
<interval></interval>
</template>
<style scoped></style>
interval.vue
<template>
<depth></depth>
</template>
<script setup>
import depth from './depth.vue';
</script>
<style>
</style>
depth.vue
<template>
{{userData}}
</template>
<script setup>
import {
inject
} from 'vue';
const userData = inject('provideUserData')
console.log(userData);
</script>
<style>
</style>
- 0
- 0
-
赞助
微信
支付宝
-
分享