vuejs 2 cómo ver los valores de la tienda de vuex


Estoy usando vuex y vuejs 2 juntos.

Soy nuevo en vuex, quiero ver un cambio de variable store.

Quiero añadir la función watch en mi vue component

Esto es lo que tengo hasta ahora:

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

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

Quiero saber si hay algún cambio en el my_state

¿Cómo puedo ver store.my_state en mi componente vuejs?

Author: raffffffff, 2017-04-07

10 answers

No debe usar los observadores del componente para escuchar el cambio de estado. Te recomiendo usar las funciones getters y luego mapearlas dentro de tu componente.

import { mapGetters } from 'vuex'

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

En tu tienda:

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

Debería poder escuchar cualquier cambio realizado en su tienda usando this.myState en su componente.

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

 52
Author: Gabriel Robert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-13 16:44:30

Digamos, por ejemplo, que tienes una cesta de frutas, y cada vez que añadas o quitas una fruta de la cesta, desea (1) mostrar información sobre el conteo de frutas, pero también (2) desea ser notificado del conteo de frutas de alguna manera elegante...

fruta-cuenta-componente.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>

Tenga en cuenta que el nombre de la función en el objeto watch, debe coincidir con el nombre de la función en el objeto computed. En el ejemplo anterior, el nombre es count.

Los valores nuevos y antiguos de una propiedad vigilada se pasarán a watch callback (la función count) como parámetros.

La tienda de cestas podría tener este aspecto:

cesta de frutas.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

Puedes leer más en los siguientes recursos:

 50
Author: Anastazy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-03 18:21:20

Como se mencionó anteriormente, no es buena idea ver los cambios directamente en la tienda

Pero en algunos casos muy raros puede ser útil para alguien, así que voy a dejar esta respuesta. Para otros casos, consulte la respuesta de @gabriel-robert

Puedes hacer esto a través de state.$watch. Agregue esto en su método created (o donde u necesita que se ejecute) en component

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.
    }
);

Más detalles: https://vuex.vuejs.org/en/api.html#vuexstore-instance-methods

 20
Author: GONG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-04 09:07:35

Creo que el asker quiere usar watch con Vuex.

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

      },
      {
        deep:true
      }
      );
 6
Author: yeahdixon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-26 15:58:15

La mejor manera de ver los cambios en la tienda es usar mapGetters como dijo Gabriel. Pero hay un caso en el que no puedes hacerlo a través de mapGetters por ejemplo, quieres obtener algo de la tienda usando el parámetro:

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

En ese caso no se puede usar mapGetters. Puedes intentar hacer algo como esto en su lugar:

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

Pero desafortunadamente todoById se actualizará solo si se cambia this.id

Si desea actualizar el componente en tal caso, use this.$store.watch solución proporcionada por Gong. O maneje su componente conscientemente y actualice this.id cuando necesite actualizar todoById.

 4
Author: Arseniy-II,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-11 01:37:20

Esto es para todas las personas que no pueden resolver su problema con getters y realmente necesitan un observador, por ejemplo, para hablar con cosas de terceros que no son de vue (ver Vue Watchers sobre cuándo usar watchers).

Los observadores del componente Vue y los valores calculados también trabajan en valores calculados. Así que no es diferente con 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);
        }
    }
}

Si solo se trata de combinar el estado local y global, el doc de mapState {[4] } también proporciona un ejemplo:

computed: {
    ...mapState({
        // to access local state with `this`, a normal function must be used
        countPlusLocalState (state) {
          return state.count + this.localCount
        }
    }
})
 4
Author: dube,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-25 20:30:31

Puede utilizar una combinación de acciones Vuex , getters, propiedades calculadas y observadores para escuchar los cambios en un valor de estado Vuex.

Código HTML:

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

Código 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()}`)
    }
  }
})

Ver JSFiddle demo .

 1
Author: Amin NAIRI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-26 13:58:14

Cuando se quiere ver a nivel de estado, se puede hacer de esta manera:

let App = new Vue({
    //...
    store,
    watch: {
        '$store.state.myState': function (newVal) {
            console.log(newVal);
            store.dispatch('handleMyStateChange');
        }
    },
    //...
});
 1
Author: Andy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-15 12:50:07

También puede usar mapState en su componente vue para obtener directamente el estado de la tienda.

En tu componente:

computed: mapState([
  'my_state'
])

Donde my_state es una variable de la tienda.

 0
Author: Eugene Kulakov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-08 19:41:35

Cree un Estado local de su variable store observando y configurando los cambios de valor. De modo que la variable local cambia para form-input v-model no muta directamente la variable de almacén .

data() {
  return {
    localState: null
  };
 },
 computed: {
  ...mapGetters({
    computedGlobalStateVariable: 'state/globalStateVariable'
  })
 },
 watch: {
  computedGlobalStateVariable: 'setLocalState'
 },
 methods: {
  setLocalState(value) {
   this.localState = Object.assign({}, value);
  }
 }
 0
Author: Mukundhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-06 10:36:34