5

In VueJs Docs, https://vuejs.org/guide/custom-directive.html I can easily create a custom directive using the native Vue.directive method

My question is how would you be able to create a custom directive inside an export default {}

the same as when registering a component or prop:

components: {
   Component1, Component2
},
methods: {
   method1() {
    // code here
   }
},
2
  • vuejs.org/examples/select2.html has an example Commented Jun 14, 2016 at 3:43
  • Yes the vue instance has a "directives" prop that works like the "components" prop Commented Jun 21, 2016 at 13:54

2 Answers 2

7

Here is a basical example about how to use directive in a component (*.vue file):

component/snippet.vue

<template>

    <div id="snippet">
        <code v-snippet>
            {{snippet.code}}
        </code>
    </div>

</template>


<script>

import snippet from '../directive/snippet';


export default {
    directives: {
        snippet: snippet
    }
}

</script>

directive/snippet.js

export default {
    
    update: function (el) {

        console.log('update');
    }
}

For further information, You can check https://v2.vuejs.org/v2/guide/custom-directive.html (the Intro part).

Sign up to request clarification or add additional context in comments.

1 Comment

There is no any reference to "snippet" in your "directive/snippet.js". So it will return error.
1

You can create a custom directive in this way

export default {
  components: {
    Component1, Component2
  },
  methods: {
    method1() {
      // code here
    }
  },
  directives: {
    // create a directive named 'elementLog'
    elementLog: {
      inserted: function (el) {
        console.log(el)
      },
    },
  },
}

In the template write the name of the directive in kebab-case format and add 'v-'

<template>
  <div>
    <span v-element-log>One</span>
    <span v-element-log>Two</span>
  </div>
</template>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.