使用计算属性和 VueX 的样式绑定

Style-Binding using Computed Properties and VueX

我如何在与 VueX 集成时使用 VueJS 中的计算属性绑定样式。

我遇到的问题是我的样式属性在我的 VueX 商店发生更改后没有更新。

代码示例:

//VueX Store
const store = new Vuex.Store({
 state : {
  div: [
   {
    offset: 0,
    width: 1,
    text : 'Hello World'
   },
   {
    offset: 0,
    width: 1,
    text : 'Hello World As Well'
   }
  ]
  }
});
//My component
<template>
 <div v-bind:style="{ width: width, left: offset}">
  <p>{{text}}</p>
 </div>
</template>

<script>
export default {
  name: 'divBox',
  computed : {
   text : function() {
    return this.$store.state.div[this.Id].text;
   },
   width : function() {
    return this.$store.state.div[this.Id].width;
   },
   offset : function() {
    return this.$store.state.div[this.Id].offset;
   }
  },
  props : ['Id']
}
</script>

这是一个工作示例,说明如何使用 vuex 执行您想要的操作。 https://jsfiddle.net/n9jmu5v7/770/ I assume your problem is the fact that your store does not contain any mutations https://vuex.vuejs.org/en/mutations.html

mutations: {
  bgChange: state => state.bg='grey',
  colorChange: state => state.color='green'
}

此外,请记住,仅仅因为您使用 vuex 并不意味着您需要将所有内容都放入其中,所以将本地数据保存在组件中是可以的。例如,组件样式信息听起来像是不需要与其他任何东西共享的东西(显然,您可能有理由将其存储在有意义的 vuex 中)。