I am wanting to create a vue directive that can be added to any HTML element in which clicking it would attach a click event to open a "related" modal component.
My directive looks like this,
import { DirectiveOptions, DirectiveBinding } from 'vue/types/options';
const handleDialogClose = () => {
console.log("do close");
};
const dialogShow: DirectiveOptions = {
bind(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
//add a keycode listerner to close dialog on "escape"
document.body.addEventListener('keyup', handleDialogClose);
//change the current dialogs data to show:true
vnode.context.$refs[binding.value][0].show = true;
},
unbind() {
document.body.removeEventListener('keyup', handleDialogClose);
}
};
export default dialogShow;
I add my directive to vue like so,
import Vue from 'vue';
import dialogShow from '../../../common/directives/src/dialogOpen';
Vue.directive('dialog-show', dialogShow);
and attach to HTML element like this <button v-dialog-show="'dialog1'">Show Dialog 1</button>
This in turn should launch the ` component, but I am getting the following error,
TypeError: Cannot read property '0' of undefined
which is getting thrown at,
vnode.context.$refs[binding.value][0].show = true;
No my understanding is that if I have more than one and directive on a page I need to access the refs array via [0] is this not correct?
I am currently building the page like this,
<div class="item" v-for="(item, index) in items" :key="index">
<button v-dialog-show="item.slug" type="button">{{ item.title }}</button>
<Dialog :item="item" :ref="item.slug" />
</div>