iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 23
2
自我挑戰組

每天來點 Vue.js 吧系列 第 23

對 Vue component 傳入非 Prop 的 attribute

tags: Vuejs

Vue component 可以傳入 prop attribute 以及 non-prop attribute 兩種 attribute,分別有以下差異:

  • prop attribute,會被作為子組件 instance 的 property,且子組件根元素中不會有該 HTML attribute 生成。
  • non-prop attribute,會作為 HTML attribute 被添加在子組件的根元素上。

兩者差異比較

下方分別傳入prop attribute 以及 non-prop attribute 兩種 attribute,可以看見作為 non-prop attributeuser-id 被添加在根元素上方,而 prop attribute name 則傳入被作為 property

  • prop attributename
  • non-prop attributeuser-id
Vue.component('my-component', {
  template: `<label for="user">user: <input type="text"  id="user" :value="name"></label>`,
  props: ['name'],
})

const vm = new Vue({
  el: '#app',
  template: `<div id="app"><my-component name="Tony" user-id="12443"/></div>`,
})

使用 $attrsinheritAttrs: falsenon-prop attribute 渲染到子組件特定元素中:

上述方法中,我們看到 non-prop attribute 會被渲染到子組件根元素上,不過若是想將其渲染到子組件特定元素中,可以使用 $attrsinheritAttrs: false 兩者達成。

先來看看兩者在官方文件的定義:

inheritAttrs: false

By default, parent scope attribute bindings that are not recognized as props will “fallthrough” and be applied to the root element of the child component as normal HTML attributes. When authoring a component that wraps a target element or another component, this may not always be the desired behavior. By setting inheritAttrs to false, this default behavior can be disabled. The attributes are available via the $attrs instance property (also new in 2.4) and can be explicitly bound to a non-root element using v-bind.

預設 inheritAttrs: true 會將 parent scope 中的 non-prop attribute 作為普通的 HTML attribute 渲染到子組件的根元素。

設置為 inheritAttrs: false 則不會產生上述行為。

$attrs

Contains parent-scope attribute bindings (except for class and style) that are not recognized (and extracted) as props. When a component doesn’t have any declared props, this essentially contains all parent-scope bindings (except for class and style), and can be passed down to an inner component via v-bind="$attrs" - useful when creating higher-order components.

包含 parent scope 中的 non-prop attribute,並可以透過 $attrs 傳入子組件。

透過結合上述兩者,可以將 non-prop attribute 綁定到 子組件 特定元素上。

Vue.component('my-component', {
  inheritAttrs: false,
  template: `<label for="user">user: <input type="text" v-bind="$attrs"  id="user"></label>`,
  props: ['name'],
  mounted() {
    console.log(this.$attrs)
  },
})

const vm = new Vue({
  el: '#app',
  template: `<div id="app"><my-component name="Tony" user-id="12443" text="test"/></div>`,
})

若是文中有任何錯誤、錯字、想討論的內容,歡迎各位大大不吝鞭笞指正、交流分享,筆者不慎感激 ✦ ✦ ✦

▶︎ 筆者 github:https://github.com/YUN-RU-TSENG
▶︎ 老王賣瓜之筆者另一篇鐵人:每天來點 CSS Specification

▶︎ 倘若不斷向深處扎根,似乎就能茁壯成長 - RM


參考資料:

  1. Vuejs.org 2.x

上一篇
Prop Validation
下一篇
Vue .sync Modifier
系列文
每天來點 Vue.js 吧30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Chris
iT邦新手 4 級 ‧ 2020-10-09 22:56:45

哦!跑去玩?(誤)

抖抖抖抖抖

我要留言

立即登入留言