Vue.js directive within a template -


based on example https://vuejs.org/examples/select2.html try create component reuse in future. unfortunately, code doesn't work.

html:

<template id="my-template">   <p>selected: {{selected}}</p>   <select v-select="selected" :options="options">     <option value="0">default</option>   </select> </template>  <div id="app">   <my-component></my-component> </div> 

vue:

vue.component('my-component', {     template: '#my-template' })  vue.directive('select', {   twoway: true,   priority: 1000,    params: ['options'],    bind: function () {     var self =     $(this.el)       .select2({         data: this.params.options       })       .on('change', function () {         self.set(this.value)       })   },   update: function (value) {     $(this.el).val(value).trigger('change')   },   unbind: function () {     $(this.el).off().select2('destroy')   } })  var vm = new vue({   el: '#app',   data: {     selected: 0,     options: [       { id: 1, text: 'hello' },       { id: 2, text: 'what' }     ]   } }) 

https://jsfiddle.net/xz62be63/

thank help!

your problem has nothing directive itself.

selected , options defined in data of vue main instance, not in data of my-component - it's not available in template.

but can pass main instance component using props:

<div id="app">   <my-component :selected.sync="selected" :options="options"></my-component>   <!-- added .sync modifier transfer value change main instance--> </div> 

and in code:

vue.component('my-component', {     template: '#my-template',     props: ['selected','options'] }) 

updated fiddle: https://jsfiddle.net/linusborg/rj1klluc/


Comments