2017-03-10 148 views
1

如何在與VueX集成的同時使用VueJS中的計算屬性綁定樣式。使用計算屬性和VueX進行樣式綁定

我遇到的問題是關於我的樣式屬性在我的VueX Store中發生更改後未更新。

代碼示例:

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

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

回答

0

下面是如何使用vuex做你想要什麼樣的工作示例。 https://jsfiddle.net/n9jmu5v7/770/我假設你的問題是你的店鋪不包含任何突變https://vuex.vuejs.org/en/mutations.html

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

另外請記住,僅僅因爲你使用vuex並不意味着你需要把一切都變成它,它是好的,保持本地數據的組件。例如,組件樣式信息聽起來像是不需要與其他任何東西共享的東西(顯然你可能有一個存儲在vuex中的理由,這是有道理的)。

+0

This Works!非常感謝! 我有突變設置BTW - >但由於某些原因,他們不能正常工作。 –

+0

@NathanielDeshpande如果這回答了這個問題,請不要忘記接受它作爲正確答案。如果你想出了更好的答案,一定要發佈它。 – qw3n