I am using Laraval custom components, for example, I have:
components/input.blade.php
<input type="text" class="rounded">
Note: this is a simple example, the key part here is that I want to reuse the HTML generated by the blade template.
Now I can create a Vue component with a scoped slot:
js/components/Search.vue
<template>
<div>
<slot name="search-input" />
</div>
</template>
<script>
export default {
methods: {
focus() {
console.log('focus input');
}
}
}
</script>
// ... and registering the component
// among others
Vue.component('search', require('js/components/Search'));
new Vue({
el: '#vue_app'
});
Now great, I can use my component as follows:
views/somepage.blade.php
<search>
<template v-slot:search>
<x-input>
</template>
</search>
All works as expected, however as you can see I have a focus method, which I would like to be triggered when focusing on the blade input.
Now I can't do this:
js/components/Search.vue
<template>
<div>
<slot name="search-input" @focus="focus" />
</div>
</template>
<script>
export default {
methods: {
focus() {
console.log('focus input');
}
}
}
</script>
But I can do this:
js/components/Search.vue
<template>
<div>
<div ref="search-container"><slot name="search-input" /></div>
</div>
</template>
<script>
export default {
methods: {
mounted() {
this.$refs['search-container'].querySelector('input').addEventListener('focus', this.focus)
},
focus() {
console.log('focus input');
}
}
}
</script>
But I am not sure that using addEventListener is the best approach within a Vue component.
Is there a better way to achieve what I am looking to do?