淺談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對象進(jìn)行解構(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)文章
vue?大文件分片上傳(斷點(diǎn)續(xù)傳、并發(fā)上傳、秒傳)
本文主要介紹了vue?大文件分片上傳,主要包括斷點(diǎn)續(xù)傳、并發(fā)上傳、秒傳,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07Vue+elementUI實現(xiàn)多圖片上傳與回顯功能(含回顯后繼續(xù)上傳或刪除)
這篇文章主要介紹了Vue+elementUI實現(xiàn)多圖片上傳與回顯功能(含回顯后繼續(xù)上傳或刪除),本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03vue2.0實現(xiàn)點(diǎn)擊其他區(qū)域關(guān)閉自定義div功能
這篇文章主要介紹了vue2.0實現(xiàn)點(diǎn)擊其他區(qū)域關(guān)閉自定義div功能實現(xiàn),本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06