Vue 透传 Attribute
Vue About 3,349 words单个元素
自定义MyButton
组件。
<template>
<button class="btn">Click me</button>
</template>
<script>
export default {
name: "MyButton"
}
</script>
<style scoped>
.btn {
height: 10px;
color: blue;
}
</style>
引用MyButton
组件。
添加了class=large
属性,该属性直接透传到MyButton
的根元素button
上(template
是占位符不是根元素)。
large
会和button
上的btn
合并,最终class
为class="btn large"
。
<template>
<MyButton class="large"></MyButton>
</template>
<script>
import MyButton from "@/components/fallthrough-attributes/MyButton";
export default {
name: "ParentComponent",
components: {MyButton}
}
</script>
<style scoped>
.large {
height: 100px;
}
</style>
实际渲染的HTML
:
<button class="btn large">Click me</button>
组件中套组件
最外层传入的属性将透传到最底下组件。
MyButton
<template>
<BaseButton v-bind="$attrs" v-on="$listeners"></BaseButton>
</template>
<script>
import BaseButton from "@/components/fallthrough-attributes/BaseButton";
export default {
name: "MyButton",
components: {BaseButton},
inheritAttrs: false,
methods: {
onMyButtonClick() {
console.log("onMyButtonClick")
}
}
}
</script>
BaseButton
<template>
<button v-on="$listeners">Base button</button>
</template>
<script>
export default {
name: "BaseButton"
}
</script>
ParentComponet
<template>
<MyButton id="xxx" class="large" @click="onParentClick" test-attr="test-attr"></MyButton>
</template>
<script>
import MyButton from "@/components/fallthrough-attributes/MyButton";
export default {
name: "ParentComponent",
components: {MyButton},
methods: {
onParentClick() {
console.log("onParentClick");
},
}
}
</script>
多个元素
多个元素需要使用div
包裹一层,并且指定attr
和listeners
传入到指定的元素。
inheritAttrs: false
:表示不自动地继承attribute
(否则直接赋值在最外层div
)。
MyButton
<template>
<div class="btn-wrapper">
<button v-bind="$attrs" v-on="$listeners" id="yyy" class="btn" @click="onMyButtonClick">Click me</button>
<p>Fallthrough attribute: {{ $attrs }}</p>
<p>Fallthrough listeners: {{ $listeners }}</p>
</div>
</template>
<script>
export default {
name: "MyButton",
inheritAttrs: false,
methods: {
onMyButtonClick() {
console.log("onMyButtonClick")
}
}
}
</script>
<style scoped>
.btn {
height: 10px;
color: blue;
}
</style>
ParentComponent
<template>
<MyButton id="xxx" class="large" @click="onParentClick" test-attr="test-attr"></MyButton>
</template>
<script>
import MyButton from "@/components/fallthrough-attributes/MyButton";
export default {
name: "ParentComponent",
components: {MyButton},
methods: {
onParentClick() {
console.log("onParentClick");
},
}
}
</script>
<style scoped>
.large {
height: 100px;
}
</style>
最终 HTML
class=large
合并在最外层div
上,其余合并属性在button
上
<div class="btn-wrapper large">
<button id="yyy" test-attr="test-attr" class="btn">Click me</button>
<p data-v-6bf75713="">Fallthrough attribute: { "id": "xxx", "test-attr": "test-attr" }</p>
<p>Fallthrough listeners: {}</p>
</div>
参考
Views: 1,091 · Posted: 2023-01-09
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...