https://vuejs.org/v2/api/#inheritAttrs
v2.4から inheritAttrsが使えるようになった。
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: false
を設定することで、属性を継承しなくなるようだ。実際にどのような挙動になるか試してみた。
js
Vue.component('inherit-attrs-link', {
inheritAttrs: true,
props: ['src'],
template: '<a :href="src">{{ src }}</a>'
})
Vue.component('not-inherit-attrs-link', {
inheritAttrs: false,
props: ['src'],
template: '<a :href="src">{{ src }}</a>'
})
new Vue({
el: '#app'
})
html
<div id="app">
<inherit-attrs-link
src="http://example.com"
href="http://inherit-href.example.com"
target="_blank"
/>
<not-inherit-attrs-link
src="http://example.com"
href="http://inherit-href.example.com"
target="_blank"
/>
</div>
Result
<a href="http://inherit-href.example.com" target="_blank">http://example.com</a>
<a href="http://example.com">http://example.com</a>
- inheritAttrs: trueの場合
- 親の属性が継承される。
- コンポーネントで指定したhrefよりも親のhref指定が優先されている。
- inheritAttrs: falseの場合
- 親の属性が継承されないため、target属性がつかなかった。
- コンポーネントで指定したhrefが反映された。
Source
See the Pen inheritAttrs by tic40 (@ccpzjoh) on CodePen.
v-bind="$attrs" を加えてみる
公式でv-bind="$attrs"
を使う例が提示されていたので、そちらの挙動も確認してみる。
js
Vue.component('inherit-attrs-link', {
inheritAttrs: true,
props: ['src'],
template: '<a v-bind="$attrs" :href="src">{{ src }}</a>'
})
Vue.component('not-inherit-attrs-link', {
inheritAttrs: false,
props: ['src'],
template: '<a v-bind="$attrs" :href="src">{{ src }}</a>'
})
html
前例と同じ
Result
<a href="http://inherit-href.example.com" target="_blank">http://example.com</a>
<a href="http://example.com" target="_blank">http://example.com</a>
- inheritAttrs: trueの場合
- inheritAttrs: falseの場合
Source
See the Pen inheritAttrs-bind$attrs by tic40 (@ccpzjoh) on CodePen.
まとめ
- 最後の例のように、受け取るprops名と、付与する属性名が異なっている場合は、
inheritAttrs: false
にして置いたほうが副作用がない。
- 基底コンポーネントは、基本的には、
inheritAttrs: false
にしておいた方が良さそう