【问题标题】:How to access store values to components in vue js如何在 vue js 中访问存储值到组件
【发布时间】:2018-08-29 07:03:42
【问题描述】:

这是我的 store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        isLoggedIn: !!localStorage.getItem('token'),
        isLog : !!localStorage.getItem('situation')
    },
    mutations: {
        loginUser (state) {
            state.isLoggedIn = true
            state.isLog = true
        },
        logoutUser (state) {
            state.isLoggedIn = false
            state.isLog = false
        },
    }
})

但是当我在 display.vue 中调用 {{state.isLoggedIn}} 时,我没有得到值。

在 display.vue 中,我使用

<script>
import axios from "axios";
import store from '../store';

export default {
  name: "BookList",
  data() {
    return {
      students: [],
      errors: [],
      state: this.state.isLoggedIn,

    };
  },
})
</script>

<template>
{{this.state}}
</template>

但是当我这样做时,我遇到了错误。请任何人都可以请帮助是什么问题。

【问题讨论】:

  • this.$store.state.isLoggedIn,见vuex.vuejs.org/guide/…(向下滚动一点)。或者,查看 mapState 助手 ~ vuex.vuejs.org/guide/state.html#the-mapstate-helper
  • 投票结束是一个错字
  • store.state.isLoggedIn 在您的情况下,因为您直接将商店导入组件
  • @dziraf 两者(即this.$storestore)都应该引用同一个对象,因为Vue.use(Vuex) 并假设OP 已将商店注入到他们的Vue 实例中

标签: vue.js vuejs2 vue-router


【解决方案1】:

您不需要将您的商店导入到您的组件中。相反,您应该使用this.$store 访问它。

要访问存储状态,更好(也是推荐的)方法是在您的组件中使用map the state

在你的例子中应该是这样的:

import { mapState } from 'vuex'

export default {
    ...
    computed: {
        ...mapState({
            isLoggedIn: 'isLoggedIn'
        })
     }
}

在您的模板中,不需要this。只需按其名称调用该属性:

{{ isLoggedIn }}

【讨论】:

  • @Jared 不,你需要 commit 到商店。您可以使用 $store.commit('your-mutation', payload) 或发送一个改变状态的 action
猜你喜欢
  • 2018-12-13
  • 2020-07-27
  • 2019-02-05
  • 2019-07-14
  • 2017-06-05
  • 1970-01-01
  • 2015-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多