Reputation: 193
I have this problem where binding ref
in renderless component won't work. I've tried adding class
within the instance object
and the class
binding work but the ref
didn't. I also tried logging this.$refs
and it just returns an empty object.
App.vue
<template>
<div id="app">
<renderless>
<div slot-scope="{ instance, logger }">
<div v-bind="instance"></div>
<button @click="logger('One')">One</button>
<button @click="logger('Two')">Two</button>
</div>
</renderless>
</div>
</template>
<script>
import Renderless from "./components/Renderless";
export default {
components: {
Renderless
},
};
</script>
components/Renderless.vue
<script>
export default {
render(h) {
return this.$scopedSlots.default({
instance: {
ref: 'container'
},
})
},
mounted() {
this.init()
},
methods: {
init() {
console.log(this.$refs)
},
logger(value) {
console.log(value)
},
},
};
</script>
How can I bind the ref
so that the child component know what element to target or any other better solutions/suggestions?
BTW code is also available on codesandbox.
Upvotes: 1
Views: 811
Reputation: 2298
You can use querySelector
and querySelectorAll
to pick out what you want within the child component. this.$el
should provide the based element of the child class once the component has mounted.
init () {
const buttons = this.$el.querySelectorAll('button');
buttons.forEach(button => {
// access each button
});
// fetches an item by element id
const itemById = this.$el.querySelector('#elementid');
// fetches by classes
const itemsByClass = this.$el.querySelector('.className');
}
Upvotes: 1