淺談Vue3 父子傳值
父傳子:
1、 在父組件的子組件標(biāo)簽上通過 :傳遞到子組件的數(shù)據(jù)名="需要傳遞的數(shù)據(jù)"
在這里為了大家區(qū)分我將父組件中的數(shù)據(jù)定義為 : fatherData ,
子組件需要接收的數(shù)據(jù)定義為: sonData 。
// 父組件
<template>
<div class="about">
{{fatherData}}
<!-- 父傳子 -->
<!-- 1、 在父組件的子組件標(biāo)簽上通過 :傳遞到子組件的數(shù)據(jù)名="需要傳遞的數(shù)據(jù)" -->
<children :sonData="fatherData"></children>
</div>
</template>
<script>
import children from "@/components/children"
import { defineComponent,reactive,toRefs } from "vue";
export default defineComponent({
components:{
children,
},
name:"about",
setup(){
const state = reactive({
fatherData:"hello"
})
return {
...toRefs(state)
}
}
})
</script>
2、子組件依舊通過 props 來接收并且在模版中使用
那么大多數(shù)情況下都會去通過父組件傳遞到子組件中的數(shù)據(jù),根據(jù)這個數(shù)據(jù)去做一些特定的功能或者請求數(shù)據(jù)等等。
在 setup 鉤子中第一個參數(shù) props 就可以訪問到父組件傳遞的數(shù)據(jù),那么在函數(shù)中也是通過: props.父組件傳遞數(shù)據(jù)的名稱 來操作該數(shù)據(jù)。
setup函數(shù)接收props作為其第一個參數(shù),props對象是響應(yīng)式的(單向的父—>子),watchEffect或watch會觀察和響應(yīng)props的更新。不要對props對象進行解構(gòu),那樣會失去響應(yīng)性。在開發(fā)過程中,props對象對用戶空間代碼時不可變的,用戶嘗試修改props時會觸發(fā)警告。
// 子組件
<template>
<div class="children">
<!-- 3、在子組件模版中使用 -->
{{sonData}}
</div>
</template>
<script>
export default {
name:"Children",
// 2、子組件通過 props 來接收
props:["sonData"],
setup(props){
function childrenbut(){
// props.sonData 可以訪問到父組件傳遞的數(shù)據(jù)
console.log(props.sonData);
}
return {
childrenbut
}
}
}
</script>
子傳父:
1、子組件觸發(fā)事件通過 setup 的第二個參數(shù) context.emit 來實現(xiàn)子傳父
context 上下文對象。
// 子組件
<template>
<div class="children">
{{sonData}}
<!-- 1、觸發(fā)事件 -->
<button @click="childrenbut">子組件按鈕</button>
</div>
</template>
<script>
export default {
name:"Children",
setup(props,context){
function childrenbut(){
console.log(context);
// 2、通過context.emit 實現(xiàn)子傳父
// 第一個參數(shù)為 方法名,第二個參數(shù)為 需要傳遞的數(shù)據(jù)
context.emit("change",'world')
}
return {
childrenbut,
}
}
}
</script>
context 也可以使用結(jié)構(gòu)的形式這樣寫
// 子組件
<script>
export default {
name:"Children",
// 通過結(jié)構(gòu) 之后直接寫 emit {emit}
setup(props,{emit}){
function childrenbut(){
// 省去 context.emit
emit("change",'world')
}
return {
childrenbut,
}
}
}
</script>
總結(jié)
在 vue3 中無論是父傳子還是子傳父其實與 vue2 中都相差無幾,
思想大多一樣,不一樣的是 vue3 需要通過調(diào)用各種各樣的鉤子來實現(xiàn)傳參
相關(guān)文章
巧妙運用v-model實現(xiàn)父子組件傳值的方法示例
這篇文章主要介紹了巧妙運用v-model實現(xiàn)父子組件傳值的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04
搭建Vue從Vue-cli到router路由護衛(wèi)的實現(xiàn)
這篇文章主要介紹了搭建Vue從Vue-cli到router路由護衛(wèi)的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
基于vue實現(xiàn)8小時帶刻度的時間軸根據(jù)當(dāng)前時間實時定位功能
這篇文章主要介紹了基于vue實現(xiàn)8小時帶刻度的時間軸根據(jù)當(dāng)前時間實時定位功能,開始時間、結(jié)束時間可配置,根據(jù)當(dāng)前時間初始化位置,本文通過實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05

