第一種:需要用到 defineProps,defineEmits;用法其實跟vue2.x基本上還是一樣的
父傳子:parent.vue
<template>
<div>
<child :value="value" @add="childClick" :msg="msg" />
<br />
<div>{{msg1}}</div>
<br />
<button @click.stop="parentClick()">父組件按鈕</button>
</div>
</template>
<script setup lang="ts">
/**
* 引入必要的模塊
*/
import { ref } from 'vue'
import child from './Child .vue'
/**
* 定義數據
*/
const value = ref<number>(0);
const msg = ref<string>('我是父組件傳遞過來的值啊~~');
const msg1 = ref<string>('')
/**
* 定義方法
*/
const parentClick = ()=> {
value.value++
}
const childClick = (value)=>{
msg1.value = value
}
</script>
子組件:child.vue
<template>
<div>
<h1>{{ props.msg }}</h1>
<h1>{{ props.value }}</h1>
<button @click="onChildClick">子組件按鈕</button>
</div>
</template>
<script setup lang="ts">
/**
* 定義數據
*/
const props = defineProps({ value: { type: Number },msg:{type:String} })
const emit = defineEmits(['add'])
/**
* 定義方法
*/
const onChildClick = ()=> {
emit('add', '我是子組件傳過來的值')
}
</script>
第二種:父級組件向多層子組件傳值 provide 和 inject
父級組件:
import { provide} from 'vue';
provide('parentMsg','我是父組件');
子組件:
import {inject} from 'vue';
const sonMsg = inject(parentMsg)
孫子組件
import {inject} from 'vue';
const grandsonMsg = inject(parentMsg)