Skip to content

Commit ab67761

Browse files
committed
add updated select2 example
1 parent 2fa6e6f commit ab67761

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

Diff for: examples/select2/index.html

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8">
5+
<title>Vue.js custom directive integration example (select2)</title>
6+
<script src="../../dist/vue.js"></script>
7+
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
8+
<link href="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet">
9+
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
10+
<style>
11+
select {
12+
min-width: 300px;
13+
}
14+
</style>
15+
</head>
16+
<body>
17+
18+
<div id="el">
19+
<p>Selected: {{selected}}</p>
20+
<select2
21+
:options="options"
22+
placeholder="select one"
23+
v-model="selected">
24+
</select2>
25+
</div>
26+
27+
<script type="x/template" id="select2-template">
28+
<select>
29+
<option v-if="placeholder"></option>
30+
<slot></slot>
31+
</select>
32+
</script>
33+
34+
<script>
35+
Vue.component('select2', {
36+
props: ['options', 'placeholder', 'value'],
37+
template: '#select2-template',
38+
mounted: function () {
39+
var vm = this
40+
Vue.nextTick(function () {
41+
$(vm.$el)
42+
// init select2
43+
.select2({
44+
data: vm.options,
45+
placeholder: vm.placeholder
46+
})
47+
// emit event on change.
48+
.on('change', function () {
49+
vm.$emit('input', mockEvent(this.value))
50+
})
51+
// set initial value
52+
.select2('val', vm.value)
53+
})
54+
},
55+
watch: {
56+
value: function (value) {
57+
// update value
58+
$(this.$el).select2('val', value)
59+
},
60+
options: function (options) {
61+
// update options
62+
$(this.$el).select2({ data: options })
63+
}
64+
},
65+
destroyed: function () {
66+
$(this.$el).off().select2('destroy')
67+
}
68+
})
69+
70+
// mock an event because the v-model binding expects
71+
// event.target.value
72+
function mockEvent (value) {
73+
return {
74+
target: {
75+
value: value
76+
}
77+
}
78+
}
79+
80+
var vm = new Vue({
81+
el: '#el',
82+
data: {
83+
selected: 0,
84+
options: [
85+
{ id: 1, text: 'Hello' },
86+
{ id: 2, text: 'World' }
87+
]
88+
}
89+
})
90+
</script>
91+
</body>
92+
</html>

0 commit comments

Comments
 (0)