Prop
-
Prop驗證
Vue.component('my-component', { props: { // 基礎的型別檢查 (`null` 和 `undefined` 會通過任何型別驗證) propA: Number, // 多個可能的型別 propB: [String, Number], // 必填的字串 propC: { type: String, required: true }, // 帶有默認值的數字 propD: { type: Number, default: 100 }, // 帶有默認值的物件 propE: { type: Object, // 物件或陣列默認值必須從一個工廠函式獲取 default: function () { return { message: 'hello' } } }, // 自定義驗證函式 propF: { validator: function (value) { // 這個值必須匹配下列字串中的一個 return ['success', 'warning', 'danger'].indexOf(value) !== -1 } } } })- prop 會在一個組件實體創建之前進行驗證
-
非 Prop 的 Attribute
-
如果一個父組件向其子組件傳遞一個屬性,但是子組件沒有使用props接收它,那么這個屬性就會被添加到子組件的根元素上去,即:在子組件使用
this.$attrs就能獲取到傳入的屬性對應的值 -
<div id="app"> <child-com :name='name' :age='age' :sex='sex'></child-com> </div> <script> const vm = new Vue({ el: '#app', // 父組件 data: { name: 'lyl', age: 20, sex: '男' }, components: { childCom: { // 子組件 template: ` <div> <span> {{name}} </span> <grand-com v-bind='$attrs'></grand-com> <!-- 注意看這里,你會發現這里的 v-bind后面直接跟上的不是一個屬性而是等號 --> <!-- 這樣一來我們就把 子組件中沒有用到的屬性(除class和style以外)全部傳到了孫子組件 --> </div> `, props: ['name'], // 這里沒有將 age 和 sex 在 props 中接收 created() { console.log(this.$attrs) // 控制臺列印:{age:20,sex:男} }, components: { grandCom: { // 孫子組件 template: ` <div> <span>{{$attrs.age}}</span> <span>{{$attrs.sex}}</span> </div> `, } } } } }) </script> -
inheritAttrs屬性的用法 -
<div id="app"> <child-com :name='name' :age='age' :sex='sex'></child-com> </div> <script> const vm = new Vue({ el: '#app', // 父組件 data: { name: 'lyl', age: 20, sex: '男' }, components: { childCom: { // 子組件 template: ` <div> <span> {{name}} </span> </div> `, props: ['name'], // 這里沒有將 age 和 sex 在 props 中接收 created() { console.log(this.$attrs) // 控制臺列印:{age:20,sex:男} } } } }) </script> -

你就會發現,這里的div標簽上面被系結了age、sex這樣的屬性,這就是官方檔案說的非Prop的屬性會被添加被系結組件的根元素上 ,就如上圖所示,但是往往你是不想這樣做的,那么就可以使用
inheritAttrs屬性了用法:在子組件的模板物件中添加
inheritAttrs: false即可讓這種情況禁止掉<div id="app"> <child-com :name='name' :age='age' :sex='sex'></child-com> </div> <script> const vm = new Vue({ el: '#app', // 父組件 data: { name: 'lyl', age: 20, sex: '男' }, components: { childCom: { // 子組件 inheritAttrs: false, // 父組件傳入的name、age、sex屬性中除子組件props接收的屬性name外,其他屬性默認會被瀏覽器渲染成html屬性,但是設定該屬性之后則不會被瀏覽器這樣渲染 template: ` <div> <span> {{name}} </span> </div> `, props: ['name'], // 這里沒有將 age 和 sex 在 props 中接收 created() { console.log(this.$attrs) // 控制臺列印:{age:20,sex:男} } } } }) </script>
-
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/154330.html
標籤:JavaScript
上一篇:自定義的可分類可搜索的下拉框組件
