Vue.js Vue:拥有依赖Vuex存储属性的组件的最佳Vuex实践

Vue.js Vue:拥有依赖Vuex存储属性的组件的最佳Vuex实践,vue.js,vuejs2,vuex,Vue.js,Vuejs2,Vuex,在这个简单组件的示例中,如果模板需要一个属性来渲染,而该属性将是Vuex存储的数据,那么最好像下面这样直接从属性中读取: <template> <div> <div> {{ this.$store.getters.getProduct.title }} </div> <div> {{ this.$store.getters.getProduct.name }}

在这个简单组件的示例中,如果模板需要一个属性来渲染,而该属性将是Vuex存储的数据,那么最好像下面这样直接从属性中读取:

<template>
   <div>
      <div>
         {{ this.$store.getters.getProduct.title }}
      </div>
      <div>
         {{ this.$store.getters.getProduct.name }}
      </div>
   </div>
</template>

{{this.$store.getters.getProduct.title}
{{this.$store.getters.getProduct.name}
或将初始数据值设置为存储值,并按如下方式使用:

<template>
   <div>
      <div>
         {{ this.currentProduct.title }}
      </div>
      <div>
         {{ this.currentProduct.name }}
      </div>
   </div>
</template>

<script>
    export default {
        data() {
            return {
                currentProduct: this.$store.getters.getProduct
            }
        }
    }
</script> 

{{this.currentProduct.title}
{{this.currentProduct.name}
导出默认值{
数据(){
返回{
currentProduct:this.$store.getters.getProduct
}
}
}

您可以使用Vuex的
映射状态
,并将其扩展到组件的计算属性中,以直接获取状态。考虑到您的商店中有一个
currentProduct
状态

<template>
  <div>
    <div>{{ currentProduct.title }}</div>
    <div>{{ currentProduct.name }}</div>
  </div>
</template>


<script>
import { mapState } from 'vuex';

export default {
  ...
  computed: {
    ...mapState(['currentProduct']).
  }
}
</script>

{{currentProduct.title}
{{currentProduct.name}
从“vuex”导入{mapState};
导出默认值{
...
计算:{
…映射状态(['currentProduct'])。
}
}

如果您想从您的状态转换一些数据,只需使用getter

OP显然在使用getters,那么为什么建议使用
mapState
?标题是“最佳Vuex实践”,OP也没有说明他想使用
getters
。仅供参考,在这种情况下,OP不需要使用
getters
,因为他只从存储中输出状态,在显示数据之前他没有转换任何数据,所以为什么要使用
getters
?我建议您在评论之前先阅读
Vuex
文档。无论如何,快乐编码.OP的代码~
this.$store.getters.getProduct.title
。他们没有显示他们的存储代码,因此无法判断他们是否在getter中执行任何操作,但他们肯定在使用它们,而不是直接声明我假设OP没有转换任何数据,因为这句话“或者将初始数据值设置为存储值,并像这样使用…”您可以发布您的答案,没有太多的努力。让OP决定哪一个是正确的,这就是stackoverflow的目的。