組件資料傳遞 Props (父傳子)
上層的 data 透過 props 往下傳,不會往上傳回 data,所以下層的資料改變不會影響到上層(data)
App.vue
1 2 3 4 5 6 7 8 9 10 11
| import PropsTest from "@/components/PropsTest.vue"; import { ref } from "vue"; export default { components: { PropsTest, }, setup() { const data = ref("hello Vue!"); return { data }; }, };
|
1
| <PropsTest :msg="data" /> // :子層屬性="父層 data"
|
PropsTest.vue
1 2 3 4 5 6
| export default { props: ["msg"], setup(props) { return { props }; }, };
|
Props 型態
props 雖可以為陣列,但建議使用物件
表示,物件可以定義型別,還能設定預設值
1 2 3
| props: { msg: String; }
|
Or
1 2 3 4 5 6
| props: { msg: { type: String, default: 'HI' } }
|
Props 定義各個型別的預設值
父層
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import PropsTest from "@/components/PropsTest.vue"; import { ref, reactive } from "vue"; export default { components: { PropsTest, }, setup() { const string = ref("string"); const boolean = ref(true); const num = ref(0); const array = reactive([]); const obj = reactive({}); const clickFn = () => {}; return { string, boolean, num, array, obj, clickFn }; }, };
|
1 2 3 4 5 6 7 8
| <PropsTest :string="string" :boolean="boolean" :num="num" :array="array" :obj="obj" :clickFn="clickFn" />
|
子層
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| export default { props: { string: { type: String, default: "string", }, boolean: { type: Boolean, default: true, }, num: { type: Number, default: 0, }, array: { type: Array, default: () => { []; }, }, obj: { type: Object, default: () => ({}), }, clickFn: { type: Function, default: () => {}, }, }, setup(props) { return { props }; }, };
|
以上是我的學習筆記,希望也有幫助到你哦 😀
Hey!想學習更多前端知識嗎?
最近 Lala 開了前端課程 👉
【實地掌握RWD - 12小時新手實戰班】👈
無論您是 0 基礎新手,又或是想學 RWD 的初學者,
我們將帶你從零開始,深入了解並掌握 RWD 響應式網頁設計的核心技術,快來一起看看吧 😊
🚀線上課程分享
線上課程可以加速學習的時間,省去了不少看文件的時間XD,以下是我推薦的一些課程
想學習更多關於前後端的線上課程,可以參考看看。
Hahow 有各式各樣類型的課程,而且是無限次數觀看,對學生或上班族而言,不用擔心被時間綁住
如果你是初學者,非常推薦六角學院哦!
剛開始轉職也是上了六角的課,非常的淺顯易懂,最重要的是,隨時還有線上的助教幫你解決問題!
Udemy 裡的課程非常的多,品質普遍不錯,且價格都滿實惠的,CP值很高!
也是很多工程師推薦的線上課程網站。