3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Vue.js】storeの変更を検知して、dataプロパティの値を変更する。【Vuex】

Posted at

はじめに

Vuexのstoreの値が変更された際、それをコンポーネント側で検知して、
コンポーネント内のdataプロパティの値を変更するサンプルです。

ソース

sample.js

const state = {
  sampleList: []
}

const getters = {
 sampleList: state => state.sampleList,
}
 
const actions = {
 SET_SAMPLE_LIST({ commit }, values) {
  commit('SET_SAMPLE_LIST',values);
 }
}
 
const mutations = {
 SET_SAMPLE_LIST(state, { values }) {
  state.sampleList = values;
 },
}
 
export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
sample.vue

// 中略・・・

<script>
export default {
  data() {
    return {
      list: {
        datasets: [
          {
            numbers: [10, 20, 30],
          }
        ],
        labels: ["Red", "Yellow", "Blue"],
      }
    };
  },
  computed: {
    sampleList: function() {
      return this.$store.getters["sample/sampleList"];
    }
  },
  watch: {
    sampleList(values) {
      if (values) {
      	let numberList = [];
        let labelList = [];
        for (let i = 0; i < values.length; i++) {
          const value = values[i];
          numberList.push(data.number);
          labelList.push(data.label);
        }
        // this.$setでdataを変更。
        this.$set(this.list.datasets[0], "numbers", numberList);
        this.$set(this.list, "labels", labelList);
      }
    }
  },
};
</script>

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?