2016-12-16 14 views
2

アイテムのリストがあり、現在選択されているスタイルにスタイルを適用したいと思います。私はまた、Vuexを使って状態を管理しています。 Vue.js 'v-bind:class'はモデルがあっても更新されません

マイリストコンポーネント:

const List = Vue.component('list', { 
    template: 
      '<template v-if="items.length > 0">' + 
       '<ul class="list-group md-col-12">' + 
        '<a href="#" v-for="(item, index) in items" class="list-group-item list-group-item-action" v-bind:class="{ active: item.isActive }" v-on:click="selectItem(index);">{{ g.text }}</a>' + 
       '</ul>' + 
      '</template>' 
    computed: { 
     items: function() { 
      return this.$store.state.items; 
     } 
    }, 
    methods: { 
     selectItem: function (index) { 
      this.$store.commit('selectItem', index); 
     } 
    } 
}); 

マイストア:

const store = new Vuex.Store({ 
    state: { 
     items: [], 
     currentIndex: -1 
    }, 
    mutations: { 
     selectItem: function(state, index) { 
      if (index === state.currentIndex) { 
       return; 
      } 
      if (state.currentIndex > -1) { 
       delete state.items[state.currentIndex].isActive; 
      } 
      state.currentIndex = index; 
      state.items[state.currentIndex].isActive = true; 
     } 
    } 
}); 

私は何もクロームデベロッパーツールでVueの「タブ」を使用して、参照することである私は、リストの項目をクリックしたときに「items」配列は正しく更新されていますが、そのクラスはクラスに設定されていません。

また、タイムトラベルのデバッグを使用してすべての突然変異を調べると、その場合にクラスが設定されます。

なぜこの動作とそれを修正するのですか?

答えて

4

私が深さでより多くのドキュメントを読んでいるはず判明します。特にChange Detection Caveats

ソリューションは、このように店の変異を変更することでした。ここに

selectItem: function(state, index) { 
    if (index === state.currentIndex) { 
     return; 
    } 
    if (state.currentIndex > -1) { 
     Vue.delete(state.items[state.currentIndex], 'isActive'); 
    } 
    state.currentIndex = index; 
    Vue.set(state.items[state.currentIndex], 'isActive', true); 
} 

キーがVue.deleteVue.set機能を使用することです。

その他の回答https://stackoverflow.com/a/40961247/525843

0

は、次の試してみてください。

const List = Vue.component('list', { 
    template: 
      '<template>' + 
       '<ul class="list-group md-col-12">' + 
        '<a href="#" v-for="(item, index) in items" class="list-group-item list-group-item-action" v-bind:class="{ active: item.isActive }" v-on:click="selectItem(index);">{{ g.text }}</a>' + 
       '</ul>' + 
      '</template>' 
+0

明日はお試しいただきありがとうございます。その間に、より多くの文脈を提供することができますか?私のテンプレートとの唯一の違いは、テンプレート要素の "v-if"を削除したことです。なぜそれが違いになるのでしょうか? – Stephan

+0

私はこれを試して、私はそれが違いがないと思った – Stephan

関連する問題