Vue 3 中的自定义指令

Custom directives in Vue 3

我正在尝试创建自定义指令以在单击元素时执行函数。我无法让它工作,我查看了自定义指令的文档,甚至直接从那里复制示例也没有用。

我正在使用单个文件模板和本地指令。这是模板:

<template>
  <div class="container">
    <div class="row">
      <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
        <button v-test:click="clicked">Click me</button>
      </div>
    </div>
  </div>
</template>

这是脚本:

<script>
  export default {
    name: 'App',
    components: {
    },
    directives: {
      test: {
        bind(el, binding) {
          const type = binding.arg;
          const fn = binding.value;
          el.addEventListener(type, fn)
        }
      }
    },
    methods: {
      clicked() {
        alert('text');
      }
    }
  }
</script>

我尝试过使用 Vue 3 语法(beforeMount 而不是绑定)以及全局指令,但这些东西似乎也不起作用。有谁知道我做错了什么?

如果我为传递给 v-test 的值提供括号,则在加载页面后会立即出现警告框。无论哪种方式,单击按钮时都不会发生任何事情。

Vue3 更改了指令的语法。 New Syntax

bind → beforeMount
inserted → mounted
beforeUpdate (new)
update (has been removed)
componentUpdated → updated
beforeUnmount (new)
unbind -> unmounted