web-dev-qa-db-ja.com

vuejs 2 vuexからストアの値を見る方法

私はvuexvuejs 2を一緒に使っています。

私はvuexに慣れていない、私はstore変数の変更を見たい。

vue componentwatch関数を追加したい

これは私がこれまでに持っているものです:

import Vue from 'vue';
import {
  MY_STATE,
} from './../../mutation-types';

export default {
  [MY_STATE](state, token) {
    state.my_state = token;
  },
};

my_stateに変更があるかどうかを知りたい

Vuejsコンポーネントでstore.my_stateを監視するにはどうすればいいですか?

100
raffffffff

たとえば、果物のかごがあり、そのかごに果物を追加または削除するたびに、(1)果物の数に関する情報を表示する、 しかし あなたも(2 )いくつかの派手な方法で果物の数の通知を受けたい...

fruit-count-component.vue

<template>
  <!-- We meet our first objective (1) by simply -->
  <!-- binding to the count property. -->
  <p>Fruits: {{ count }}</p>
</template>

<script>
import basket from '../resources/fruit-basket'

export default () {
  computed: {
    count () {
      return basket.state.fruits.length
      // Or return basket.getters.fruitsCount
      // (depends on your design decisions).
    }
  },
  watch: {
    count (newCount, oldCount) {
      // Our fancy notification (2).
      console.log(`We have ${newCount} fruits now, yaay!`)
    }
  }
}
</script>

watchオブジェクト内の関数の名前は、computedオブジェクト内の関数の名前と一致しなければならないことに注意してください。上の例では、名前はcountです。

監視プロパティの新しい値と古い値は、パラメータとして監視コールバック(count関数)に渡されます。

バスケットストアは次のようになります。

fruit-basket.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const basket = new Vuex.Store({
  state: {
    fruits: []
  },
  getters: {
    fruitsCount (state) {
      return state.fruits.length
    }
  }
  // Obvously you would need some mutations and actions,
  // but to make example cleaner I'll skip this part.
})

export default basket

以下のリソースでもっと読むことができます。

107
Anastazy

状態の変化を監視するためにコンポーネントのウォッチャーを使用しないでください。ゲッター関数を使用してから、それらをコンポーネント内にマッピングすることをお勧めします。

import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters({
      myState: 'getMyState'
    })
  }
}

あなたの店で:

const getters = {
  getMyState: state => state.my_state
}

あなたのコンポーネントでthis.myStateを使うことによってあなたのストアに行われたどんな変更にも耳を傾けることができるはずです。

https://vuex.vuejs.org/en/getters.html#the-mapgetters-helper

62
Gabriel Robert

上で述べたように、ストアで直接変更を監視することはお勧めできません

ただし、ごくまれに、誰かに役立つことがあるので、この回答を残します。その他の場合は、@ gabriel-robert回答を参照してください

あなたはstate.$watchを通してこれをすることができます。これをコンポーネントのcreated(またはこれを実行するのに必要な場所)メソッドに追加します。

this.$store.watch(
    function (state) {
        return state.my_state;
    },
    function () {
        //do something on data change
    },
    {
        deep: true //add this if u need to watch object properties change etc.
    }
);

詳細: https://vuex.vuejs.org/en/api.html#vuex-store-instance-methods

33
GONG

質問者はVuexでwatchを使用したいと思います。

this.$store.watch(
      (state)=>{
        return this.$store.getters.your_getter
      },
      (val)=>{
       //something changed do something

      },
      {
        deep:true
      }
      );
12
yeahdixon

これは、ゲッターで問題を解決することができず、実際にウォッチャーが本当に必要なすべての人々のためのものです。非vueサードパーティのものと話をする( Vue Watchers を参照してくださいwatchersを使用する場合)。

Vueコンポーネントのウォッチャーと計算値はどちらも計算値に対しても機能します。だからvuexと違いはありません:

import { mapState } from 'vuex';

export default {
    computed: {
        ...mapState(['somestate']),
        someComputedLocalState() {
            // is triggered whenever the store state changes
            return this.somestate + ' works too';
        }
    },
    watch: {
        somestate(val, oldVal) {
            // is triggered whenever the store state changes
            console.log('do stuff', val, oldVal);
        }
    }
}

ローカル状態とグローバル状態を組み合わせることだけを考えている場合は、 mapStateのドキュメント にも例があります。

computed: {
    ...mapState({
        // to access local state with `this`, a normal function must be used
        countPlusLocalState (state) {
          return state.count + this.localCount
        }
    }
})
7
dube

Gabrielが言ったように、店舗の変更を監視する最良の方法はmapGettersを使うことです。しかし、mapGettersでできない場合もあります。あなたはパラメータを使用してストアから何かを取得したいです。

getters: {
  getTodoById: (state, getters) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

その場合はmapGettersは使えません。あなたは代わりにこのようなことをしようとするかもしれません:

computed: {
    todoById() {
        return this.$store.getters.getTodoById(this.id)
    }
}

しかし残念ながらtodoByIdthis.idが変更された場合にのみ更新されます

そのような場合にコンポーネントをアップデートしたい場合はthis.$store.watchGong提供のソリューション を使用してください。 todoByIdを更新する必要があるときは、コンポーネントを意識的に扱い、this.idを更新してください。

4
Arseniy-II

値の変更を確認して設定することで、ストア変数の Local state を作成します。ローカル変数が form-input v-model に変更されても、 store変数 は直接変更されません。

data() {
  return {
    localState: null
  };
 },
 computed: {
  ...mapGetters({
    computedGlobalStateVariable: 'state/globalStateVariable'
  })
 },
 watch: {
  computedGlobalStateVariable: 'setLocalState'
 },
 methods: {
  setLocalState(value) {
   this.localState = Object.assign({}, value);
  }
 }
3
Mukundhan

次のように簡単です:

watch: {
  '$store.state.drawer': function() {
    console.log(this.$store.state.drawer)
  }
}
2
micah5

Vuexの状態値の変化を監視するには、Vuex actionsgetters計算プロパティ および watchers の組み合わせを使用できます。

HTMLコード:

<div id="app" :style='style'>
  <input v-model='computedColor' type="text" placeholder='Background Color'>
</div>

JavaScriptコード:

'use strict'

Vue.use(Vuex)

const { mapGetters, mapActions, Store } = Vuex

new Vue({
    el: '#app',
  store: new Store({
    state: {
      color: 'red'
    },
    getters: {
      color({color}) {
        return color
      }
    },
    mutations: {
      setColor(state, payload) {
        state.color = payload
      }
    },
    actions: {
      setColor({commit}, payload) {
        commit('setColor', payload)
      }
    }
  }),
  methods: {
    ...mapGetters([
        'color'
    ]),
    ...mapActions([
        'setColor'
    ])
  },
  computed: {
    computedColor: {
        set(value) {
        this.setColor(value)
      },
      get() {
        return this.color()
      }
    },
    style() {
        return `background-color: ${this.computedColor};`
    }
  },
  watch: {
    computedColor() {
        console.log(`Watcher in use @${new Date().getTime()}`)
    }
  }
})

JSFiddleデモを参照してください

1
Amin NAIRI

州レベルで見たいときは、こうすることができます。

let App = new Vue({
    //...
    store,
    watch: {
        '$store.state.myState': function (newVal) {
            console.log(newVal);
            store.dispatch('handleMyStateChange');
        }
    },
    //...
});
1
Andy

ストアの突然変異を購読することもできます。

store.subscribe((mutation, state) => {
  console.log(mutation.type)
  console.log(mutation.payload)
})

https://vuex.vuejs.org/api/#subscribe

0
alloyking

VueコンポーネントでmapStateを使用して、ストアから状態を取得するように指示することもできます。

あなたのコンポーネントで:

computed: mapState([
  'my_state'
])

my_stateはストアからの変数です。

0
Eugene Kulakov