vue.js - 登录成功后没有调用数据库
问题描述
在用户登录我的 SPA 后,我很难对我的数据库发起 axios 调用。
- 路由(gaplist/3)将用户带到一个页面(gaplist.vue),该页面检测用户是否登录。
- 如果未登录,则会显示登录表单。
- 一旦输入的用户名/密码组合被接受,用户就会被“推送”到同一页面(gaplist/3)
- 在这里,登录状态被检测到——这就是一切都失败的地方——对数据库的调用将返回一堆与用户关联的记录和参数“3”。
不幸的是,最后一步并没有完全发生。检测到登录状态,但未进行数据库调用。只有当我刷新页面时,才会进行调用并显示结果。
我在这里没有掌握什么概念?
谢谢,汤姆。
我的代码如下:
GapList.vue(路线:gaplist/3)
<template>
<v-content>
<v-container fluid fill-height>
<v-layout justify-center>
<v-flex xs12 sm6>
<h1>Production and sale of produce</h1>
<v-card flat>
<div v-if="isIn">
<p v-for="(card, id) in cards">{{card.product}}</p>
<logout-button></logout-button>
</div>
<div v-else>
<gap-login :gapid=gapid></gap-login>
</div>
</v-card>
</v-flex>
</v-layout>
</v-container>
</v-content>
</template>
<script>
import GapLogin from '../components/gap/GapLogin';
import LogoutButton from '../components/gap/LogoutButton'
export default {
name: 'GapList',
components: {
GapLogin,
LogoutButton
},
data () {
return {
gapid: this.$route.params.id,
cards: [],
lang: this.$i18n.locale,
bNoRecords: false,
}
},
created(){
this.loadCrops(this.gapid,this.lang)
},
computed: {
isIn : function(){ return this.$store.getters.isLoggedIn},
},
methods: {
loadCrops(gapid,lang){
var vm = this;
if (this.isIn){
axios.get('/gapcroplist/' + gapid)
.then(function (resp) {
vm.cards = resp.data;
})
.catch(function (resp) {
vm.bNoRecords = true;
});
}
},
}
}
</script>
GapLogin.vue
<template>
<div class="formdiv">
<v-layout justify-center>
<h3>Login</h3>
<v-card flat>
<v-alert
v-if="loginError"
:value="true"
type="error"
transition="scale-transition"
dismissible
>
You didn't enter correct information
</v-alert>
<v-form class="login" @submit.prevent="login">
<v-text-field
v-model="form.email"
type="email"
label="Email"
required
autofocus
></v-text-field>
<v-text-field
v-model="form.password"
type="password"
label="Password"
required
></v-text-field>
<v-btn
type="submit"
>Login in </v-btn>
</v-form>
</v-card>
</v-layout>
</div>
</template>
<script>
export default {
name: "GapLogin",
props: ['gapid'],
data() {
return {
form: {
email: null,
password: null
},
loginError:false
}
},
methods: {
login: function () {
this.loginError = false
this.$store.dispatch('login', this.form)
.then(() =>
{this.$router.push({path: '/gaplist/' + this.gapid})
})
.catch(err => {
this.loginError = true
}
)
},
}
}
</script>
解决方案
更新的答案:
created
hook 不会被再次调用。使用updated
也会导致错误,因为您会触发另一个更新并有一个无限循环。
我建议您发出一个completed
事件,而不是推送到同一条路线:
在您的login
方法中,then
而不是$router.push
:
this.$emit('completed')
并在 -component 上注册事件gap-login
:
<gap-login @completed="completed" :gapid=gapid></gap-login>
并将该方法添加到GapList.vue
-file:
completed () {
this.loadCrops(this.gapid, this.lang)
}
您axios
在全球范围内使用,但它似乎不存在。
尝试使用this.$axios
:
this.$axios.get('/gapcroplist/' + gapid)