[英]$emit an event from child to parent component Vue 2
我是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');
我没有收到任何错误消息或任何东西-只是不起作用。
谢谢
好的,所以感谢@Patrick Steele,我已经弄清楚了。
我没有使用$ on-哎呀。
将代码添加到了mounted()部分,现在可以使用:
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();
$this.on('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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.