如何在渲染时向嵌套的Vue组件添加指令



如何在不更改myDivhtml的情况下将v-b-tooltip.hover指令添加到myInputmyButton?我一直试图在render函数中访问它们,但使用api并不明显。

更新:添加第二个组件

Vue.component('other-component', {
template: "<div><b-form-input title='myInput'/><b-button title='myButton'>Button</b-button></div>"
})
var MyComponent = {
render: function(createElement) {
console.log(this.$slots.default.children);
return createElement("div", this.$slots.default)
}
}
new Vue({
el: "#app",
components: {
MyComponent
}
})
<!-- Load required Bootstrap and BootstrapVue CSS -->
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<!-- Load Vue followed by BootstrapVue -->
<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<div id="app">
<my-component>
<other-component />
</my-component>
</div>

您可以修改插槽vnode来实现这一点。

const MyComponent = {
render(h) {
let buttonVNode = this.$slots.default[0].children[2]
buttonVNode.data.directives = [{
name: 'b-tooltip',
value: 'Tooltip Content!'
}]
return h('div', this.$slots.default)
}
}

JSFiddle中的示例。

如果您想要更通用的东西,例如通过其id属性查找vnode,则可能需要使用递归并检查每个vnode子级。

最新更新