Laravel 和 axios 在提交后清除表单
Laravel and axios clear Form after submit
在我的 Laravel 应用程序中,我正在提交一个带有 vue 和 axios 的表单。
提交后我想清除表单中的输入字段,但它不会工作。
HTML:
<form method="post" enctype="multipart/form-data" v-on:submit.prevent="addPost">
<textarea id="post_area" v-model="content"></textarea>
.....
</form>
JS:
const app = new Vue({
el: '#app',
data: {
content: '',
posts: []
},
......
.then(function (response) {
if(response.status===200) {
//reload posts
app.posts = response.data;
this.content = '';
}
})
它只是不会清除输入字段。
this
未指向您的 Promise 成功回调中的 vue 实例
改用箭头函数。箭头函数在词法上绑定 this
的值
const app = new Vue({
el: '#app',
data: {
content: '',
posts: []
},
......
.then( (response) => {
if(response.status===200) {
//reload posts
app.posts = response.data;
this.content = '';
}
})
或者创建一个指向正确 vue 实例的局部变量,并使用它来访问您的数据 属性,如下所示:
methods:{
addPost(){
var vm = this;
//.....axios post
.then( (response) => {
if(response.status===200) {
//reload posts
app.posts = response.data;
vm.content = '';
}
})
}
}
在我的 Laravel 应用程序中,我正在提交一个带有 vue 和 axios 的表单。 提交后我想清除表单中的输入字段,但它不会工作。
HTML:
<form method="post" enctype="multipart/form-data" v-on:submit.prevent="addPost">
<textarea id="post_area" v-model="content"></textarea>
.....
</form>
JS:
const app = new Vue({
el: '#app',
data: {
content: '',
posts: []
},
......
.then(function (response) {
if(response.status===200) {
//reload posts
app.posts = response.data;
this.content = '';
}
})
它只是不会清除输入字段。
this
未指向您的 Promise 成功回调中的 vue 实例
改用箭头函数。箭头函数在词法上绑定 this
的值
const app = new Vue({
el: '#app',
data: {
content: '',
posts: []
},
......
.then( (response) => {
if(response.status===200) {
//reload posts
app.posts = response.data;
this.content = '';
}
})
或者创建一个指向正确 vue 实例的局部变量,并使用它来访问您的数据 属性,如下所示:
methods:{
addPost(){
var vm = this;
//.....axios post
.then( (response) => {
if(response.status===200) {
//reload posts
app.posts = response.data;
vm.content = '';
}
})
}
}