Vue?props傳遞的類型和寫法分享
更新時間:2024年07月26日 11:29:11 作者:D_jing20
這篇文章主要介紹了Vue?props傳遞的類型和寫法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Vue props傳遞的類型和寫法
props常用屬性
類型檢查(規(guī)定數(shù)據(jù)類型)
| 類型檢查(規(guī)定數(shù)據(jù)類型) | type | String 字符串 |
| Number 數(shù)字 | ||
| Boolean 布爾 | ||
| Array 數(shù)組 | ||
| Object 對象 | ||
| Date 日期 | ||
| Function 函數(shù) | ||
| Symbol 獨一無二的值(es6) | ||
| 默認值 | default | default : (默認值),基礎數(shù)據(jù)類型: 直接賦值,對象數(shù)據(jù)類型: 用函數(shù)賦值 ()=>[] |
| 必填項 | required | required: (必填項) ,默認為false,說明父級必須傳入,否則會報錯 |
| 校驗 | validator | 驗證傳入的值是否符合規(guī)定 |
props語法
props: {
prop1: [Boolean, Number], // 多個類型
prop2: {
type: Number, // 數(shù)字
default: 100 // 默認值
},
prop3: {
type: Boolean, // 布爾
required: true // 必填
},
prop4: {
type: String, // 字符串
required: true
},
prop5: {
type: Array, // 數(shù)組 // 對象或數(shù)組默認值必須從一個工廠函數(shù)獲取
default: () => []
},
prop6: {
type: Object, // 對象 // 對象或數(shù)組默認值必須從一個工廠函數(shù)獲取
default: function () {
return { msg: 'hello' }
}
},
prop7: {
type: String,
validator: function (t) { // 自定義驗證函數(shù)
return t === 'fade' || t === 'slide' // 這個值必須匹配下列字符串中的一個
},
defalut:'slide'
}
}Vue props 傳遞函數(shù)
Props的type是函數(shù)
通過 props 傳遞 函數(shù) 看看有啥用。
// 父組件
</template>
<div>
<children :add='childrenClick'></children>
<p>{{countF}}</p>
</div>
</template>
<script>
import children from './Children'
export default {
name: 'HelloWorld',
data() {
return {
countF: 0,
}
},
methods: {
childrenClick(c){
this.countF += c;
}
},
components:{
children,
}
}
</script>
// 子組件
<template>
<div>
<button @click="handClick(count)">點擊加 1 </button>
</div>
</template>
<script>
export default {
data() {
return {
count:1,
}
},
props:{
add:{
type: Function
}
},
methods: {
handClick(){
this.add( ++this.count); // 父組件方法
}
},
}

可以看到 chirden 組件在中 使用 props.add() , 調用的是 父組件的方法。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
在Vue中延遲執(zhí)行某個函數(shù)的實現(xiàn)方式
在Vue中延遲執(zhí)行某個函數(shù),你可以使用setTimeout()函數(shù)或者Vue提供的生命周期鉤子函數(shù),本文通過一些示例代碼給大家介紹的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下2023-12-12
vue用addRoutes實現(xiàn)動態(tài)路由的示例
本篇文章主要介紹了vue用addRoutes實現(xiàn)動態(tài)路由的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09

