【发布时间】:2018-06-24 02:06:49
【问题描述】:
在我的 Laravel-Vuejs 项目中使用 EventBus。在成功创建 Item 后,我从 ItemCreate 组件发出 items-updated 事件。在同一页面上,我使用了ItemList 组件,它显示了创建的Items 列表
代码如下:
app.js 文件
require('./bootstrap');
window.Vue = require('vue');
window.EventBus = new 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'
});
ItemCreate.vue 组件
export default {
data: function () {
return {
itemName: ''
}
},
methods: {sendItemData: function () {
axios.post('/dashboard/item', {
name: this.itemName
})
.then(response => {
if (response.status === 201) {
toastr.success('Item created successfully!', {timeout: 2000});
EventBus.$emit('items-updated');
}
})
.catch(error => {
toastr.error(error, 'Ooops! Something went wrong!');
})
}
}
}
ItemList.vue 组件
export default {
data: function () {
return {
items: [],
}
},
methods: {
getItems: function () {
axios.get('/dashboard/items')
.then(response => {
this.items = response.data;
})
.catch(error => {
toastr.error(error, 'Ooops! Something went wrong!');
})
}
},
mounted() {
this.getItems();
EventBus.$on('items-updated', function () {
this.getItems();
});
}
}
【问题讨论】:
-
"this" 指的是不同的东西,具体取决于调用它的时间/地点。如果要使其保持一致,则必须在自己的变量中保存对正确 this 的引用。对于更正的代码,请参阅@lostbyte 的答案。
-
如果你使用 vue-resource 而不是 axios,这不会发生,因为 vue-resource 甚至在 http 回调方法中也将“this”设置为当前组件。
标签: laravel-5 vue.js vue-component