Pass data to a directive? Pass data to a directive? vue.js vue.js

Pass data to a directive?


The value is a regular JavaScript expression. This way, if you want to pass a string, say 'test', use:

v-my-directive="'test'"

Demo:

Vue.directive('my-directive', function (el, binding) {  console.log('directive expression:', binding.value)  // => "test"})new Vue({  el: '#app',  data: {    message: 'Hello Vue.js!'  }})
<script src="https://unpkg.com/vue"></script><div id="app">  <p>{{ message }}</p>  <div v-my-directive="'test'"></div></div>


You have to quote the string, otherwise it will look for the test variable in your component context (its props or data):

v-my-directive="'test'"

Inside your custom directive, you can access the passed value as in the binding.value:

Vue.directive('demo', {  bind: function (el, binding, vnode) {    var s = JSON.stringify    el.innerHTML =      'name: '       + s(binding.name) + '<br>' +      'value: '      + s(binding.value) + '<br>' +      'expression: ' + s(binding.expression) + '<br>' +      'argument: '   + s(binding.arg) + '<br>' +      'modifiers: '  + s(binding.modifiers) + '<br>' +      'vnode keys: ' + Object.keys(vnode).join(', ')  }})

See the Custom Directives chapter of the guide.