第一次使用 Vue cli 3 和 vuex 并尝试使用 vuex 进行简单的登录,但是我设置的 getter 没有从 vuex 存储中获取任何数据,即使状态发生变化也不会返回任何内容。
这是我的store.ts
:
export default new Vuex.Store({
state: {
loggedIn: true,
email: 'test',
password: 'test',
},
getters: {
loggedIn(state) {
return state.loggedIn;
},
userEmail(state) {
return state.email;
},
},
mutations: {
login(state, user) {
state.loggedIn = true;
state.email = user.e;
state.password = user.p;
},
logout(state) {
state.loggedIn = false;
},
},
actions: {
login(context, data) {
context.commit('login', data);
},
logout(context) {
context.commit('logout');
},
},
});
和 navbar.vue 我试图根据用户是否登录来更改导航。
html
<template>
<nav id="nav" class="navbar fixed-top navbar-expand-md navbar-light bg-light">
<router-link to="/" class="navbar-brand">Navbar</router-link>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#topNav" aria-controls="topNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="topNav">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<router-link to="/" class="nav-link">Home</router-link>
</li>
<li class="nav-item" v-if="loggedIn">
<router-link to="/Dashboard" class="nav-link">Dashboard</router-link>
</li>
<li class="nav-item" v-else>
<router-link to="/Login" class="nav-link">Login</router-link>
</li>
<li class="nav-item">
<p class="nav-link">user : {{ test }}</p>
</li>
</ul>
</div>
</nav>
</template>
打字稿
import { Component, Vue } from 'vue-property-decorator';
import { mapState, mapGetters } from 'vuex';
@Component({
computed: mapState(['loggedIn']),
})
@Component
export default class NavBar extends Vue {
private test: string = 'test';
constructor() {
super();
}
}