2016-04-06 33 views
0

基於此示例https://vuejs.org/examples/select2.html 我嘗試創建組件供將來重新使用。 不幸的是,我的代碼不起作用。模板中的Vue.js指令

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/

感謝您的幫助!

回答

1

你的問題與指令本身無關。

selectedoptions在您的Vue主實例的數據中定義,而不是在my-component的數據中定義 - 因此它在其模板中不可用。

但是你可以從主實例中使用的道具將它傳遞給組件:

<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> 

,並在代碼:

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

更新小提琴:https://jsfiddle.net/Linusborg/rj1kLLuc/

+0

謝謝,萊納斯!你的解釋對我來說非常有用! – Mugik

+0

另外:檢查jQuery的版本。由於我的小提琴包含jquery v2.1.4,因此即使使用空數據,jquery-select2也未初始化。 – Mugik