IT박스

vuejs 2 vuex에서 상점 값을 보는 방법

itboxs 2020. 7. 12. 10:22
반응형

vuejs 2 vuex에서 상점 값을 보는 방법


나는 함께 사용 vuex하고 vuejs 2있습니다.

나는 처음에 변수 변화 vuex를보고 싶습니다 store.

watch내 기능 을 추가하고 싶습니다vue component

이것이 내가 지금까지 가진 것입니다.

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

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

변경 사항이 있는지 알고 싶습니다. my_state

어떻게 봐야하지 store.my_state내 vuejs 구성 요소?


예를 들어 과일 바구니가 있고 바구니에서 과일을 추가하거나 제거 할 때마다 (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입니다.

감시 속성의 새 값과 이전 값은 매개 변수로 시계 콜백 (카운트 함수)에 전달됩니다.

바구니 상점은 다음과 같습니다.

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

다음 리소스에서 자세한 내용을 읽을 수 있습니다.


상태 변경을 청취하기 위해 구성 요소 감시자를 사용해서는 안됩니다. getters 함수를 사용한 다음 컴포넌트 내부에 맵핑하는 것이 좋습니다.

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


위에서 언급했듯이 상점에서 직접 변경 사항을 보는 것은 좋지 않습니다.

그러나 매우 드문 경우이지만 누군가에게 유용 할 수 있으므로이 답변을 남겨 두겠습니다. 다른 경우에는 @ 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/api/#watch


나는 asker가 Vuex와 함께 시계를 사용하고 싶다고 생각합니다.

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

      },
      {
        deep:true
      }
      );

이것은 게터에 대한 문제를 해결할 수없고 실제로 비가 아닌 제 3 자와 대화하기 위해 실제로 감시자가 필요한 모든 사람들을위한 것입니다 ( 감시자 를 사용할 때 Vue 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
        }
    }
})

값 변경을보고 설정하여 상점 변수 로컬 상태작성하십시오 . 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);
  }
 }

상점 변경 사항을 보는 가장 좋은 방법 mapGetters은 Gabriel이 말한대로 사용 하는 것입니다. 그러나 당신이 그것을 할 수없는 경우가 있습니다 mapGetters: 예 들어 매개 변수를 사용하여 상점에서 무언가를 얻고 싶습니다 :

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

이 경우을 사용할 수 없습니다 mapGetters. 대신 다음과 같은 작업을 시도 할 수 있습니다.

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

그러나 불행히도 변경 todoById 된 경우에만 업데이트됩니다this.id

If you want you component update in such case use this.$store.watch solution provided by Gong. Or handle your component consciously and update this.id when you need to update todoById.


It's as simple as:

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

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.


When you want to watch on state level, it can be done this way:

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

You could also subscribe to the store mutations:

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

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


if you use typescript then you can :

import { Watch } from "vue-property-decorator";

..

@Watch("$store.state.something")
private watchSomething() {
   // use this.$store.state.something for access
   ...
}


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.

참고URL : https://stackoverflow.com/questions/43270159/vuejs-2-how-to-watch-store-values-from-vuex

반응형