:::
5. 父組件→子組件間的參數傳遞(props)
- 父組件:利用
<PropsTest :msg="data" />將參數傳到PropsTest組件<script> import PropsTestfrom "@/components/PropsTest.vue"; import { ref } from "vue"; export default { components: { PropsTest, }, setup() { const data= ref('我要傳到子組件'); return { data }; }, }; </script> <template> <PropsTest :msg="data" /> </template> - 子組件:在組建中定義
props物件,並傳入setup()中,再return給樣板中呼叫使用<script> export default { props:{ msg:{ type: String, default: '我是預設文字' } }, setup(props) { return { props }; }, }; </script> <template> <h1>{{ props.msg }}</h1> </template> - 定義 props 有以下方法:(注意,若型別是
[陣列]跟{物件},要用函式的方式去設定預設值,{物件}更必須 return 一個預設的物件才行)props: { // 基礎的類型檢查 (`null` 和 `undefined` 會通過任何類型驗證) propA: Number, // 多個可能的類型 propB: [String, Number], // 必填的字符串 propC: { type: String, required: true }, // 帶有默認值的數字 propD: { type: Number, default: 100 }, // 帶有默認值的陣列 propE: { type: Array, // 對象或數組默認值必須從一個工廠函數獲取 default: () => [] }, // 帶有默認值的對象 propF: { type: Object, // 對象或數組默認值必須從一個工廠函數獲取 default: ()=> ({}) }, // 具有默認值的函數 propG: { type: Function, // 與對象或數組默認值不同,這不是一個工廠函數 —— 這是一個用作默認值的函數 default: ()=> {} }, // 自定義驗證函數 propH: { validator: function(value) { // 這個值必須匹配下列字符串中的一個 return ['success', 'warning', 'danger'].indexOf(value) !== -1 } } } - 若是有參數要在兩個子組件中傳遞(或共用),可以將該參數設到父組件中,然後再由父組件傳遞給個別子組件。
4-2 scss 用法