嗨,我正尝试使用axios更改vue包装器组件的下拉菜单。这是我的代码。
<html>
<head>
<title>title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</style>
</head>
<body>
<div id="el"></div>
<script type="text/x-template" id="demo-template">
<div>
<p>Selected: {{ input.selected }}</p>
<select2 :options="options" v-model="input.selected">
<option disabled value="0">Select one</option>
</select2>
</div>
</script>
<script type="text/x-template" id="select2-template">
<select>
<slot></slot>
</select>
</script>
<script src="http://themestarz.net/html/craigs/assets/js/jquery-3.3.1.min.js"></script>
<script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
Vue.component('select2', {
props: ['options', 'value'],
template: '#select2-template',
mounted: function () {
var vm = this;
$(this.$el)
// init select2
.select2({data: this.options})
.val(this.value)
.trigger('change')
// emit event on change.
.on('change', function () {
vm.$emit('input', this.value)
})
},
watch: {
value: function (value) {
// update value
$(this.$el)
.val(value)
.trigger('change')
},
options: function (options) {
// update options
$(this.$el).empty().select2({data: options})
}
},
destroyed: function () {
$(this.$el).off().select2('destroy')
}
});
var vm = new Vue({
el: '#el',
template: '#demo-template',
data: {
input: {
selected: "all"
},
options: []
},
created: function () {
this.mymethod();
},
methods: {
mymethod: function () {
var vm = this;
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(function (response) {
vm.options = [
{id: 'all', text: 'All'},
{id: 1, text: 'Hello'},
{id: 2, text: 'World'},
{id: 3, text: 'Bye'}
];
vm.input.selected = 2;
})
.catch(function (error) {
console.log(error);
});
}
}
});
</script>
</body>
</html>
我遇到的问题是,当我尝试添加选定的项目时,它在axios中不起作用。而且它在axios外部正常工作。
vm.input.selected = 2;
如图所示,我最初选择了全部。认为ajax调用无关紧要,所以我降低了代码复杂度。谢谢。
答案 0 :(得分:1)
您需要在input
内重新创建axios
对象:
vm.input = { selected: 2 };
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(function (response) {
vm.options = [
{id: 'all', text: 'All'},
{id: 1, text: 'Hello'},
{id: 2, text: 'World'},
{id: 3, text: 'Bye'}
];
// recreate the 'input' object for reactivity
vm.input = { selected: 2 };
})
.catch(function (error) {
console.log(error);
});
答案 1 :(得分:1)
使用Vue.set(vm.input,'selected',value)(或vm。$ set)更新对象的属性。
答案 2 :(得分:1)
好像我的包装器组件有问题。在组件的监视中更改选项和值的顺序后,此问题已解决。如果将来有人遇到相同的问题,我会添加它。
watch: {
options: function(options) {
// update options
$(this.$el).empty().select2({
data: options
})
},
value: function(value) {
// update value
$(this.$el)
.val(value)
.trigger('change')
}
},