Feofilakt
Feofilakt

Reputation: 1387

How to add directive to nested Vue components on render?

How to add v-b-tooltip.hover directive to myInput and myButton without changing myDiv html? I've been trying to access them in render function but using api turns out not obvious.

Updated: added second component

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>

Upvotes: 0

Views: 1100

Answers (1)

User 28
User 28

Reputation: 5158

You can modify the slot vnode to achieve this.

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)
  }
}

Example in JSFiddle.

If you want something more general such as find the vnode by their id attribute you may need to use recursive and check for each vnode children.

Upvotes: 1

Related Questions