1

Based on this example https://vuejs.org/examples/select2.html I try to create component for reuse in a future. Unfortunately, my 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
    $(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 you for any help!

1 Answer 1

1

your problem has nothing to do with the directive itself.

selected and options is defined in the data of your Vue main instance, not in the data of my-component - so it's not available in its template.

But you can pass it from the main instance to the component using props:

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

and in the code:

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

updated fiddle: https://jsfiddle.net/Linusborg/rj1kLLuc/

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

2 Comments

Thank you, Linus! Your explanations are very useful for me!
In addition: check the version of jQuery. Because of my fiddle include jquery v2.1.4 the jquery-select2 didn't initialized even with empty data.

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.