【问题标题】:How to pass store values in components如何在组件中传递存储值
【发布时间】:2019-01-14 01:59:12
【问题描述】:

我想在组件中传递 store.state 中的值,但出现错误: [Vue warn]: Error in render: "TypeError: Cannot read property 'state' of undefined"

所以我直接调用了组件中的值,还是不行。

const store = new Vuex.Store({
	state: {
    filter: {
      selected: false,
      value: 'test'
    }
  },
});

new Vue({
	el: '#app',
	template: `<div id="app"><div :selected="this.$store.state.filter.selected">Option</div></div>`
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>
<div id="app"></div>

Vue

const store = new Vuex.Store({
    state: {
            filter: {
                value: 'test',
                selected: true
            }
        },
    mutations: {},
    actions: {},
    getters: {}
});

HTML

<option :selected="store.state.filter.selected">{{store.state.filter.value}}</option>

我可以这样使用它吗,或者我需要换一种思路以及如何使用?谢谢。

我目前的解决方案是将值存储在计算变量中,但有没有办法将 Vuex 存储值直接传递到组件中?

computed: {
    filter () {
        return storeLogs.state.filter;
    }
}
<option :selected="filter.selected">{{filter.value}}</option>

【问题讨论】:

  • 您可以使用this.$store.state.filter.selected调用存储数据
  • 当我将其更改为 &lt;option :selected="this.$store.state.filter.selected"&gt;&lt;/option&gt; 时,它不起作用。错误是 TypeError: Cannot read property 'state' of undefined
  • 你必须同时更改{{this.$store.state.filter.value}}
  • 还是同样的错误
  • :/你能把你的项目上传到codesandbox还是我可以从teamviewer或者其他...

标签: vuejs2 vue-component vuex


【解决方案1】:

两件事:

  1. 您必须将 store 对象传递给 Vue 构造函数
  2. 无需在模板中引用“this”
const store = new Vuex.Store({
    state: {
      filter: {
        selected: false,
        value: 'test'
      }
    },
});

new Vue({
    store, // add store object to Vue
    el: '#app',
    template: `<div id="app"><div selected="$store.state.filter.selected">Option</div></div>`
});

你也可以在你的 .vue 文件中像这样使用mapState

<!-- MyComponent.vue -->
<template>
  <option :selected="filter.selected">{{filter.value}}</option>
</template>

<script>
import { mapState } from 'vuex';
export default {
  name : 'MyComponent',
  computed() {
    ...mapState(['filter'])
  }
}
</script>

【讨论】:

  • 谢谢,这是一个非常直接的答案。
猜你喜欢
  • 1970-01-01
  • 2018-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2019-07-23
相关资源
最近更新 更多