首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >vue中自定义指令的修饰符

vue中自定义指令的修饰符
EN

Stack Overflow用户
提问于 2018-10-23 18:30:03
回答 1查看 2.7K关注 0票数 4

我正在处理自定义指令,并希望创建一个这样的命令,您可以根据在标记中传递它的内容使用单独的事件来触发它。

代码语言:javascript
复制
v-example-directive.mousedown="exampleFunction"
v-example-directive.mouseup="exampleFunction"
v-example-directive.click="exampleFunction"

我看过Vue文档,并试图搜索如何做到这一点,但没有发现任何这方面的东西。是否可以这样做,以便您可以创建一个指令,并在内部具有多个函数,或者能够定义您想要的事件类型?或者我必须注册多个指令才能实现这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-23 18:53:56

您可以通过在自定义vue指令中使用argsmodifiers来实现这一点。

要使用这些钩子,您必须查看指令的binding参数。此参数包括一整套属性,您可以使用它来烘焙自定义指令。

在您的示例中,您可能希望根据所需的binding.modifier结构查找binding.argbinding.arg

参数标记:<img v-example-directive:mouseup> 修饰符标记:<img v-example-directive.mouseup>

既然添加了“标志”,就可以在指令中检查它:

代码语言:javascript
复制
Vue.directive('example-directive', {
  bind(el, binding) {
    if (binding.arg == 'mouseup') {} // Using argument markup
    if (binding.modifiers.mouseup) {} // Using modifier markup
  }
})

示例:

代码语言:javascript
复制
Vue.directive('example-directive', {
    bind(el, binding) {
        if (binding.arg == 'mousedown') { // Check by argument given to directive
          el.addEventListener("mousedown", () => {
            binding.value() // The function provided by the directive
          });
        }else if (binding.modifiers.mouseup) { //check by modifier 
          el.addEventListener("mouseup", () => {
            binding.value()
          });
        }
    }
})

let x = new Vue({
  el:"#app",
  methods: {
    clicked() {
      console.log("clicked")
    }
  }
})
代码语言:javascript
复制
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<div id="app">
<button v-example-directive:mousedown="clicked">mousedown</button>
<button v-example-directive.mouseup="clicked">mouseup</button>
<!-- ... -->
</div>

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52955664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档