首頁  >  問答  >  主體

javascript - 使用vuex提示讀不到state屬性?

使用vuex進行狀態管理
但是一直報錯不知道哪錯了


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的設定(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 }
})
習慣沉默習慣沉默2734 天前739

全部回覆(1)我來回復

  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:39:11

    或許你應該這樣調用?

    computed: mapState({ user: state => state.user.user })

    回覆
    0
  • 取消回覆