vue.js 2 how to watch store values from vuex

后端 未结 18 2138
傲寒
傲寒 2020-11-27 10:26

I am using vuex and vuejs 2 together.

I am new to vuex, I want to watch a store variable change.

I want t

相关标签:
18条回答
  • 2020-11-27 10:54

    You can also use mapState in your vue component to direct getting state from store.

    In your component:

    computed: mapState([
      'my_state'
    ])
    

    Where my_state is a variable from the store.

    0 讨论(0)
  • 2020-11-27 10:56

    This is for all the people that cannot solve their problem with getters and actually really need a watcher, e.g. to talk to non-vue third party stuff (see Vue Watchers on when to use watchers).

    Vue component's watchers and computed values both also work on computed values. So it's no different with 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);
            }
        }
    }
    

    if it's only about combining local and global state, the mapState's doc also provides an example:

    computed: {
        ...mapState({
            // to access local state with `this`, a normal function must be used
            countPlusLocalState (state) {
              return state.count + this.localCount
            }
        }
    })
    
    0 讨论(0)
  • 2020-11-27 11:01

    If you simply want to watch a state property and then act within the component accordingly to the changes of that property then see the example below.

    In store.js:

    export const state = () => ({
     isClosed: false
    })
    export const mutations = {
     closeWindow(state, payload) {
      state.isClosed = payload
     }
    }
    

    In this scenario, I am creating a boolean state property that I am going to change in different places in the application like so:

    this.$store.commit('closeWindow', true)
    

    Now, if I need to watch that state property in some other component and then change the local property I would write the following in the mounted hook:

    mounted() {
     this.$store.watch(
      state => state.isClosed,
      (value) => {
       if (value) { this.localProperty = 'edit' }
      }
     )
    }
    

    Firstly, I am setting a watcher on the state property and then in the callback function I use the value of that property to change the localProperty.

    I hope it helps!

    0 讨论(0)
  • 2020-11-27 11:03

    I think the asker wants to use watch with Vuex.

    this.$store.watch(
          (state)=>{
            return this.$store.getters.your_getter
          },
          (val)=>{
           //something changed do something
    
          },
          {
            deep:true
          }
          );
    
    0 讨论(0)
  • 2020-11-27 11:07

    You can use a combination of Vuex actions, getters, computed properties and watchers to listen to changes on a Vuex state value.

    HTML Code:

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

    JavaScript Code:

    '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()}`)
        }
      }
    })
    

    See JSFiddle demo.

    0 讨论(0)
  • 2020-11-27 11:07

    ====== store =====
    import Vue from 'vue'
    import Vuex from 'vuex'
    import axios from 'axios'
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      state: {
        showRegisterLoginPage: true,
        user: null,
        allitem: null,
        productShow: null,
        userCart: null
      },
      mutations: {
        SET_USERS(state, payload) {
          state.user = payload
        },
        HIDE_LOGIN(state) {
          state.showRegisterLoginPage = false
        },
        SHOW_LOGIN(state) {
          state.showRegisterLoginPage = true
        },
        SET_ALLITEM(state, payload) {
          state.allitem = payload
        },
        SET_PRODUCTSHOW(state, payload) {
          state.productShow = payload
        },
        SET_USERCART(state, payload) {
          state.userCart = payload
        }
      },
      actions: {
        getUserLogin({ commit }) {
          axios({
            method: 'get',
            url: 'http://localhost:3000/users',
            headers: {
              token: localStorage.getItem('token')
            }
          })
            .then(({ data }) => {
              // console.log(data)
              commit('SET_USERS', data)
            })
            .catch(err => {
              console.log(err)
            })
        },
        addItem({ dispatch }, payload) {
          let formData = new FormData()
          formData.append('name', payload.name)
          formData.append('file', payload.file)
          formData.append('category', payload.category)
          formData.append('price', payload.price)
          formData.append('stock', payload.stock)
          formData.append('description', payload.description)
          axios({
            method: 'post',
            url: 'http://localhost:3000/products',
            data: formData,
            headers: {
              token: localStorage.getItem('token')
            }
          })
            .then(({ data }) => {
              // console.log('data hasbeen created ', data)
              dispatch('getAllItem')
            })
            .catch(err => {
              console.log(err)
            })
        },
        getAllItem({ commit }) {
          axios({
            method: 'get',
            url: 'http://localhost:3000/products'
          })
            .then(({ data }) => {
              // console.log(data)
              commit('SET_ALLITEM', data)
            })
            .catch(err => {
              console.log(err)
            })
        },
        addUserCart({ dispatch }, { payload, productId }) {
          let newCart = {
            count: payload
          }
          // console.log('ini dari store nya', productId)
    
          axios({
            method: 'post',
            url: `http://localhost:3000/transactions/${productId}`,
            data: newCart,
            headers: {
              token: localStorage.getItem('token')
            }
          })
            .then(({ data }) => {
              dispatch('getUserCart')
              // console.log('cart hasbeen added ', data)
            })
            .catch(err => {
              console.log(err)
            })
        },
        getUserCart({ commit }) {
          axios({
            method: 'get',
            url: 'http://localhost:3000/transactions/user',
            headers: {
              token: localStorage.getItem('token')
            }
          })
            .then(({ data }) => {
              // console.log(data)
              commit('SET_USERCART', data)
            })
            .catch(err => {
              console.log(err)
            })
        },
        cartCheckout({ commit, dispatch }, transactionId) {
          let count = null
          axios({
            method: 'post',
            url: `http://localhost:3000/transactions/checkout/${transactionId}`,
            headers: {
              token: localStorage.getItem('token')
            },
            data: {
              sesuatu: 'sesuatu'
            }
          })
            .then(({ data }) => {
              count = data.count
              console.log(count, data)
    
              dispatch('getUserCart')
            })
            .catch(err => {
              console.log(err)
            })
        },
        deleteTransactions({ dispatch }, transactionId) {
          axios({
            method: 'delete',
            url: `http://localhost:3000/transactions/${transactionId}`,
            headers: {
              token: localStorage.getItem('token')
            }
          })
            .then(({ data }) => {
              console.log('success delete')
    
              dispatch('getUserCart')
            })
            .catch(err => {
              console.log(err)
            })
        }
      },
      modules: {}
    })

    0 讨论(0)
提交回复
热议问题