我的应用在app.js
中声明如下Vue.component('sale', require('./components/Sale.vue'));
const app = new Vue({
el: '#app',
data: {
showModal: false
},
});
我的主要index.blade文件@yields我的视图的内容,这个视图只包含我的自定义组件
<sale v-if="showModal" @hide="showModal=false"></sale>
正如您所看到的,它使用showModal
来确定何时在主页面上显示模态表单。
此处的组件使用表单提交选项声明:
<template name="sale">
<form class="form-horizontal" role="form" action="/sales/save" method="POST" @submit.prevent="save">
正确调用此save方法,axios post正在成功运行。
我在模态页面中有一个标准表单,方法在这里声明,你可以看到使用axios发布到我的控制器 - 再次,帖子是成功的。
methods: {
close(){
this.$emit('hide');
},
save(){
console.log('SOLD');
console.log(this.$data);
axios.post('/sales/save', this.$data)
.then(function (response) {
this.$emit('hide');
})
.catch(function(error) {
console.log('NO ' , error);
});
}
}
close方法也可以正常工作,使用emit更改showModal
的值,关闭对话框。
什么不起作用,就是在帖子之后,.then
函数给出了一个错误,同时调用emit:TypeError: Cannot read property '$emit' of undefined
。
事实上,.catch
正在捕捉.then
函数内部的发出错误(不是我所期待的 - 它会捕获axios POST错误)。
一旦axios调用成功,基本上我不确定如何以相同的方式关闭模态。
编辑:添加:
mounted() {
const self = this;
}
并更改了发射参考
self.$emit('hide');
我不确定我理解该帖子的其余部分
答案 0 :(得分:3)
您认为this
是指Vue实例,但在回调中并非如此。您在常规函数中丢失了this
引用。
您可以使用以下解决方案之一保留this
:
1)使用箭头功能:
methods: {
fetchData: function() {
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(text => console.log(this)) // Vue instance
}
}
2)将this
保存到变量:
methods: {
fetchData: function() {
const self = this; // save reference
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(function(text) {
console.log(self) // Vue instance; 'this' points to global object (Window)
})
}
}
答案 1 :(得分:2)
考虑到您使用的是ES2015,您只需使用箭头功能即可确保您不会创建新的this
上下文:
axios.post('/sales/save', this.$data)
.then(response => {
this.$emit('hide');
})
.catch(error => {
console.log('NO ' , error);
});
您可以在https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
找到有关箭头功能的更多信息答案 2 :(得分:1)
您的更新中的代码无效的原因是self
的范围是mounted()
,但您尝试在methods.save()
内使用它。
这样可行:
methods: {
save() {
var self = this;
axios.post('/sales/save', this.$data)
.then(function (response) {
self.$emit('hide');
})
//...
或者,如果您正在使用ES6转换器,则可以使用arrow functions来完全避免范围界定问题(箭头函数不会绑定自己的this
。)
methods: {
save() {
axios.post('/sales/save', this.$data)
.then((response) => {
this.$emit('hide');
})