【发布时间】:2017-07-07 07:22:05
【问题描述】:
我是 JS 和 Vue 的新手,所以请多多包涵:)
我有一个使用两个 Vue 组件呈现的表,它们是父级(表 - 订单)和子级(行 - 订单)。
可以在表格的每一行上按下一个按钮,该按钮对该行执行 AJAX,但我还需要在执行操作时刷新表格(父级),以便它具有更新的数据.
我认为我需要在子级中使用 $emit 将操作传递给父级,但我无法让它工作。这是代码(对不起,太长了,我删除了所有不必要的东西);
const order = {
template: `
...// table content
<td><button class="btn btn-default btn-sm" @click="assignAdvisor(id,
selectedOption)">Set Advisor</button></td>
`,
methods: {
// following is the method that is run when the button is pressed
assignAdvisor(id, selectedOption) {
axios.post('url').then(response => {
..// show response message
orders.$emit('refreshAfterUpdate'); // also tried
// this.$parent.$emit(...)
})
},
};
const orders = {
components: { order, },
props: {
orders: {
type: Object,
},
},
mounted() {
// this is basically the code that I need to re-run when button is pressed,
// which I have repeated below in a method
var refresh = () => {
axios.get('/admin/ajax/unassigned-orders')
.then(response => {
this.ordersData = response.data;
setTimeout(refresh, 5000);
});
}
refresh();
},
methods: {
refreshAfterUpdate() {
axios.get('/admin/ajax/unassigned-orders')
.then(response => {
this.ordersData = response.data;
console.log(response);
});
},
}
};
new Vue({
render(createElement) {
const props = {
orders: {
type: Object,
},
};
return createElement(orders, { props });
},
}).$mount('#unassignedOrders');
我没有收到任何错误消息或任何东西 - 它只是不起作用。
谢谢
【问题讨论】:
-
我没有看到任何使用
$on method捕获事件的代码。 -
@PatrickSteele 啊,这听起来可能是问题所在。我认为 emit 会在父节点中运行 refreshAfterUpdate 方法?
-
不,
$emit接受一个“事件名称”,并且可以选择附加参数。 “eventName”的$on处理程序可以调用刷新。
标签: javascript vue.js