Vue.js - Emit event from directive

后端 未结 7 434
北海茫月
北海茫月 2021-02-02 12:37

Is it possible to emit a custom event from the directive in the component to which this directive is attached.

I was expecting it to work as described

相关标签:
7条回答
  • 2021-02-02 13:34

    @euvl's solution is fine, but i think it's easier and cleaner to just pass a function as an argument to your directive. Seems to simplify the interface to your directive as well.

    <script>
      Vue.directive('foo', {
        bind(el, binding) {
          setTimeout(() => {
            binding.value();
          }, 3000);
        }
      });
    </script>
    
    <template>
      <button v-foo="change">{{label}}</button>
    </template>
    
    <script>
      export default{
        data() {
          return {
            label: 'i dont work'
          }
        },
        methods: {
          change() {
            this.label = 'I DO WORK!';
          }
        }
      }
    </script>
    
    0 讨论(0)
提交回复
热议问题