我想要定义一个vue指令,该指令在单击时切换弹出窗口的显示,我现在拥有的是:
toggle.js
export default {
bind(el, binding) {
console.log(binding.value); // this is undefined
el.onclick = function() {
console.log(binding.value); // this is undefined as well
// toggle menu element display
};
}
};component.vue
<template>
<button v-toggle="$refs.menu">
...
</button>
<div ref="menu">
...
</div>
</template>
<script>
import Toggle from 'path/to/toggle.js';
export default {
name: "Component",
directives: {
Toggle
}
</script>在绑定函数binding.value中总是没有定义,可能是因为菜单引用还没有准备好。这样做的正确方法是什么?
发布于 2018-10-22 18:22:50
在设置指令时不会填充$refs。您可以使它的表达式成为一个函数,它将在单击发生时计算$refs.menu,而不是在指令设置时计算。
new Vue({
el: '#app',
directives: {
toggle: {
bind(el, binding) {
el.onclick = function() {
const target = binding.value();
target.classList.toggle('closed');
};
}
}
}
});.closed {
display: none;
}<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
<button v-toggle="() => $refs.menu">
Button
</button>
<div ref="menu">
Some junk in the menu
</div>
</div>
https://stackoverflow.com/questions/52933500
复制相似问题