【发布时间】:2018-01-15 09:35:22
【问题描述】:
我在 Laravel 5.5 中使用 VueJS。我在同一页面中使用了两个组件。其中一个创建项目,另一个按顺序列出项目。所以我想要实现的是当Item创建成功时,ItemList组件应该更新自己并通过发出AJAX请求来获取最新的项目。
在ItemCreate组件ItemCreate.vue:
methods: {
sendItemData: function () {
this.$emit('items-updated');
axios.post('/dashboard/item', {
name: this.itemName,
})
.then(function (response) {
if (response.status === 201) {
toastr.success('Crawler created successfully!', {timeout: 2000});
this.$emit('items-updated');
}
})
.catch(function (error) {
toastr.error(error, 'Ooops! Something went wrong!');
})
}
在ItemList组件上ItemList.vue:
methods: {
getItems: function () {
axios.get('/items')
.then(function (response) {
this.items = response.data;
})
.catch(function (error) {
toastr.error(error, 'Ooops! Something went wrong!');
})
},
},
mounted() {
this.$on('items-updated', function () {
this.getItems();
})
}
最后这里是主要的app.js 设置:
require('./bootstrap');
window.Vue = require('vue');
Vue.component('item-list',
require('./components/entities/item/ItemList'));
Vue.component('item-create',
require('./components/entities/item/ItemCreate'));
const app = new Vue({
el: '#app'
});
【问题讨论】: