vuex加载存储状态变异的子组件

时间:2017-12-10 17:38:19

标签: vuejs2 state store vuex

我使用vuex来跟踪网格列表切换器按钮的状态。 每次选择视图类型时我都希望在模板之间切换,但这在我的情况下不起作用。这是模板

<div class="users-container">
    <div v-if="$store.state.view === 'list'">
        <h5>list</h5>
         <data-table :columns="columns" ajax="/api/v1/users/datatable"></data-table>
    </div>
    <div v-else>
        <h5>grid</h5>
        <data-grid :roles = "roles"></data-grid>
    </div>
</div>

如果我检查状态,一切都完美更新,但切换不会发生。我在这种情况下做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试使用computed属性来观察状态的变化。

&#13;
&#13;
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    view: 'list'
  },
  mutations: {
    CHANGE_VIEW (state, type) {
      state.view = type
    },
  }
});

Vue.component('list-view', {
  template: `
    <div>
      <h5>List</h5>
      <ul>
        <li v-for="item in dummyData">{{item}}</li>
      </ul>
    </div>
  `,
  data() {
    return {
      dummyData: [1, 2, 3, 4, 5]
    }
  }
})

Vue.component('grid-view', {
  template: `
    <div>
      <h5>Grid</h5>
      <table>
        <tr v-for="item in dummyData"><td>{{item}}</td></tr>
      </table>
    </div>
  `,
  data() {
    return {
      dummyData: [1, 2, 3, 4, 5]
    }
  }
})

const app = new Vue({
  el: '#app',
  store,
  data: {
    dummyData: [1, 2, 3, 4, 5]
  },
  computed: {
    view() { return this.$store.state.view }
  },
  methods: {
    changeView(type) {
      this.$store.commit('CHANGE_VIEW', type)
    }
  }
})
&#13;
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.min.js"></script>


<div id="app">
  <div class="control">
    <p>Change to:</p> 
    <button v-on:click="changeView('list')">List</button>
    <button v-on:click="changeView('grid')">Grid</button>
  </div>
  <div class="users-container">
    <div v-if="view === 'list'">
      <list-view></list-view>
    </div>
    <div v-else>
      <grid-view></grid-view>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;