在吸气剂中访问状态属性

时间:2020-04-07 09:27:19

标签: vue.js vuex

我对Vue.js和Vuex还是很陌生,我现在正尝试按照教程来解释Vuex。每当我尝试访问getter messageUpperCase时,它都不再呈现该页面。

<template>
  <div id="app">
    <h1>{{ welcome }}</h1>
    <h2>{{ message }}</h2>
    <h3>Getter: {{ messageCaps }}</h3>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      welcome: "Hello world"
    };
  },
  computed: {
    message() {
      return this.$store.state.message;
    },
    messageCaps() {
      return this.$store.getter.messageUpperCase;
    }
  },
  store: {
    state: {
      message: "Hello from vuex",
      count: 0
    },
    mutations: {},
    actions: {},
    getters: {
      messageUpperCase(state) {
        // return state.message.toUpperCase();
        return this.$store.state.message.toUpperCase()
      }
    }
  }
};
</script>

如何在吸气剂state.message中访问messageUpperCase

1 个答案:

答案 0 :(得分:3)

请按照指南将vuex添加到您的项目中:https://vuex.vuejs.org/guide/

您可以将其添加到Vue发起的位置,就像这样

import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
      message: "Hello from vuex",
      count: 0
    },
    mutations: {},
    actions: {},
    getters: {
      messageUpperCase: state => {
        // return state.message.toUpperCase();
        return state.message.toUpperCase()
      }
    }
})

并在像这样启动Vue时包含

new Vue({
    el: '#your-id',
    store,
    render: h => h(App)
});

回答您的问题:

messageUpperCase: state => {
  // return state.message.toUpperCase();
  return state.message.toUpperCase()
}