Heim > Fragen und Antworten > Hauptteil
Vuex für die Zustandsverwaltung verwenden
Aber ich erhalte ständig Fehler und weiß nicht, was falsch ist
index.vue
<template>
<p>
<v-header title="首页">
<router-link slot="right" to="/home">{{user.name}}</router-link>
</v-header>
<p class="login-msg">
<router-link to="/login">请登录</router-link>
</p>
<p class="msg" v-if="user.id">
哈哈,恭喜你已经入坑Vue2
</p>
</p>
</template>
<script>
import { mapState } from 'vuex'
export default {
data() {
return {
logo:''
}
},
computed: mapState({ user: state => state.user }),
}
</script>
vuex-Einstellungen (index.js, user.js)
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'
Vue.use(Vuex)
export default new Vuex.Store({
strict:process.env.NODE_ENV!=='production',//在非生产环境下,使用严格模式
modules:{
user
}
})
user.js
import Vue from 'vue'
export const USER_SIGNIN = 'USER_SIGNIN' //登录成功
export const USER_SIGNOUT = 'USER_SIGNOUT' //退出登录
export default {
state:{
user:JSON.parse(sessionStorage.getItem('user')) || {}
},
mutations: {
[USER_SIGNIN](state, user) {
sessionStorage.setItem('user', JSON.stringify(user))
Object.assign(state, user)
},
[USER_SIGNOUT](state) {
sessionStorage.removeItem('user')
Object.keys(state).forEach(k => Vue.delete(state, k))
}
},
actions: {
[USER_SIGNIN]({commit}, user) {
commit(USER_SIGNIN, user)
},
[USER_SIGNOUT]({commit}) {
commit(USER_SIGNOUT)
}
}
}
main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import vHeader from './components/vHeader'
Vue.config.productionTip = false
// 全局注册组件
Vue.component('vHeader',vHeader)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})