【问题标题】:Is it possible to manage local state within Vue component by VuexVuex 是否可以在 Vue 组件中管理本地状态
【发布时间】:2020-01-13 01:42:34
【问题描述】:

目前,我正在使用 Vuex 来管理应用程序级状态。

我只需要在 Vue 组件生命周期内存储数据。是否可以在不涉及全局存储的情况下使用 Vuex 来存储本地组件状态?

例如,我有一个这样的组件:

class SomeComponent extends Vue {
  id = this.$props.componentId;
  localData = {};

  async created() {
    this.localData = await apiClient.getDataById(this.id);
  }
}

然后我可以使用具有不同 prop componentId 的组件,并且每个组件都应该管理自己的状态。

<SomeComponent componentId="1" />
<SomeComponent componentId="2" />
<SomeComponent componentId="3" />

我希望看到如此理想的变体:

import LocalStore from './local-store';

class SomeComponent extends Vue {
  id = this.$props.componentId;
  localStore = new LocalStore(); // <- this is the Vuex store

  created() {
    localStore.getDataById(this.id);
  }
}

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    是的,这绝对是可能的。我从未使用过基于类的语法,但在基于对象的语法中,它看起来像这样

    <div>
      <p>{{ state1 }}<p>
      <p>{{ state2 }}</p>
      <p>{{ localState }}</p>
    </div>
    
    export default {
      computed: {
        state1() {
          return this.$store.state.state1;
        }
        state2() {
          return this.$store.state.state2;
        }
      },
      data() {
        return {
           localState: 3
        }
      },
      props: {
        componentId: {
          type: Number
      },
    }
    

    再一次,我从未使用过类基语法,但它可能看起来像这样的伪代码

    import { Prop } from 'vue-class-component'
    
    export default class App extends Vue {
      get state1() {
        return this.$store.state.state1;
      }
      get state2() {
        return this.$store.state.state2;
      }
    
      localState = 3
    
      @Prop()
      componentId: Number
    }
    

    【讨论】:

    • 谢谢。我想我错误地描述了这个问题。我想使用 Vuex 作为本地状态,而不是内置的 Vue 数据状态。
    • @Ky6uk 哦,我明白了。呃,我不认为这是可能的(我希望我能给出一个明确的答案,因为我以前没有尝试过以这种方式构建应用程序)。您可能可以通过this.$store.state.variable 或其他方式访问状态,但它不会是被动的。 vuex 与 vue 的耦合非常紧密,所以也许你想购买另一个状态管理解决方案或改变你的方法
    猜你喜欢
    • 2021-08-18
    • 2020-03-19
    • 2020-03-12
    • 2019-12-24
    • 2018-03-10
    • 2018-08-31
    • 1970-01-01
    • 2019-03-14
    • 2021-07-29
    相关资源
    最近更新 更多