vue/examples/select2/index.html

93 lines
2.2 KiB
HTML
Raw Normal View History

2016-04-16 06:30:09 +08:00
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vue.js custom directive integration example (select2)</title>
<script src="../../dist/vue.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
2016-04-16 06:30:09 +08:00
<style>
2016-04-29 08:45:24 +08:00
html, body {
font: 13px/18px sans-serif;
}
2016-04-16 06:30:09 +08:00
select {
min-width: 300px;
}
</style>
</head>
<body>
<div id="el">
</div>
<script type="text/x-template" id="demo-template">
2016-04-17 01:26:17 +08:00
<div>
<p>Selected: {{ selected }}</p>
<select2 :options="options" v-model="selected">
<option disabled value="0">Select one</option>
</select2>
</div>
</script>
2016-04-16 14:44:48 +08:00
<script type="text/x-template" id="select2-template">
2016-04-16 06:30:09 +08:00
<select>
<slot></slot>
</select>
</script>
<script>
Vue.component('select2', {
2016-04-17 01:26:17 +08:00
props: ['options', 'value'],
2016-04-16 06:30:09 +08:00
template: '#select2-template',
2016-05-10 23:26:00 +08:00
mounted: function () {
2016-04-16 06:30:09 +08:00
var vm = this
2016-04-16 06:37:58 +08:00
$(this.$el)
2016-04-17 01:26:17 +08:00
.val(this.value)
2016-04-16 06:37:58 +08:00
// init select2
2016-04-17 01:26:17 +08:00
.select2({ data: this.options })
2016-04-16 06:37:58 +08:00
// emit event on change.
.on('change', function () {
vm.$emit('input', mockEvent(this.value))
})
2016-04-16 06:30:09 +08:00
},
watch: {
value: function (value) {
// update value
$(this.$el).select2('val', value)
},
options: function (options) {
// update options
$(this.$el).select2({ data: options })
}
},
destroyed: function () {
$(this.$el).off().select2('destroy')
}
})
// mock an event because the v-model binding expects
// event.target.value
function mockEvent (value) {
return {
target: {
value: value
}
}
}
var vm = new Vue({
el: '#el',
2016-04-17 01:26:17 +08:00
template: '#demo-template',
2016-04-16 06:30:09 +08:00
data: {
selected: 0,
options: [
{ id: 1, text: 'Hello' },
{ id: 2, text: 'World' }
]
}
})
</script>
</body>
</html>