Vue.js 在此之后,$axios.post重定向到其他页面时出现问题
发布后无法移动页面 $axios.post之后,重定向到其他页面时出现问题 我的代码有问题吗Vue.js 在此之后,$axios.post重定向到其他页面时出现问题,vue.js,redirect,post,nuxt.js,vue-router,Vue.js,Redirect,Post,Nuxt.js,Vue Router,发布后无法移动页面 $axios.post之后,重定向到其他页面时出现问题 我的代码有问题吗 <template> <v-form ref="form" v-model="valid" lazy-validation @submit="formSubmit"> <v-container fluid> <v-layout row wrap> <v
<template>
<v-form ref="form" v-model="valid" lazy-validation @submit="formSubmit">
<v-container fluid>
<v-layout row wrap>
<v-flex xs12 sm12 md5>
<v-text-field v-model="nameMale" :counter="10" :rules="nameRules" label="Name Male" required box />
</v-flex>
<v-flex xs12>
<v-text-field
v-model="placeAddress"
:rules="addressRules"
label="Address"
required
box
/>
</v-flex>
</v-layout>
<v-layout row>
<v-btn type="submit" :disabled="!valid" color="primary" @click="validate">
POST
</v-btn>
<v-btn color="normal" to="./">
LIST
</v-btn>
</v-layout>
</v-container>
</v-form>
</template>
<script>
export default {
data: () => ({
valid: true,
nameMale: '',
nameRules: [
v => !!v || 'name',
],
placeAddress: '',
}),
methods: {
async formSubmit() {
const data = {
nameMale: this.nameMale,
placeAddress: this.placeAddress,
}
const apiUrl = 'http://127.0.0.1:3100/post'
await this.$axios
.post(apiUrl, data)
.then(response => {
console.log(response)
if (response.status === '200') { //<<------ 200 Okay!
this.$router.push('/list') //<<------ Can't redirect
}
})
.catch(error => {
if (error.response) {
console.log(error.response.data)
console.log(error.response.status)
console.log(error.response.headers)
} else if (error.request) {
console.log(error.request)
} else {
console.log('Error', error.message)
}
console.log(error.config)
})
},
validate() {
if (this.$refs.form.validate()) {
this.snackbar = true
}
}
}
}
您正在使用async await,因此请将您的await包装在一个try-catch中:
async method(){
try {
await function
this.$router.push()
} catch {
console.log(‘an error’)
}
有同样的问题。我认为问题在于您不能在axios中引用
$this
或$this.router
。要解决这个问题,请在调用axios之前创建一个变量,并在axios中使用该变量,如下所示
var self = this;
var store = this.$store;
var router = this.$router; --------------------- create var like this.
axios({
...
}).then(res => {
//do something here
router.push('/link'); ----------------------------- use it like this.
}).catch(err => { console.log(err) }
让我知道这是否解决了你的问题
var self = this;
var store = this.$store;
var router = this.$router; --------------------- create var like this.
axios({
...
}).then(res => {
//do something here
router.push('/link'); ----------------------------- use it like this.
}).catch(err => { console.log(err) }