source

Vuex: Store에서 컴포넌트 데이터 또는 호출 컴포넌트 메서드를 업데이트하는 방법

goodcode 2022. 8. 24. 23:54
반응형

Vuex: Store에서 컴포넌트 데이터 또는 호출 컴포넌트 메서드를 업데이트하는 방법

매장이 있는 경우:

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    foo: bar
  },
  mutations: {
    updateComponent (state) {
      // computation and logic
      // update state
      this.$refs.myComponent.updateComponent(state.foo)
    }
  }
}

참조가 'myComponent'인 구성 요소가 있습니다.

<template>
  ...
</template>
<script>
  export default {
    ...
    methods: {
      updateComponent(payload) {
        // do stuff
      }
    }
  }
</script>

스토어에서 update Component() 메서드를 호출하고 싶습니다.사용할 수 있습니다.this.$refs.myComponent다른 보기 및 구성 요소에서 사용되지만 스토어에서는 작동하지 않습니다.에러가 발생하다TypeError: Cannot read property 'myComponent' of undefined.

확실히.this에 대한 올바른 범위가 아닙니다.this.$refs.myComponent사용할 때 사용합니다.

전화해도 될까요?updateComponent()어떻게요?

사용할 수 있습니다.vuex의 서브스크라이브 메서드탑재 단계에서 컴포넌트를 서브스크라이브합니다.

mounted() {
    this.$store.subscribe((mutation, state) => {
        switch(mutation.type) {
          case 'updateComponent':
            // Update your component with new state data
          break;
        } 
     })
  }

참고 자료: https://vuex.vuejs.org/api/ #http://https://vuex.vuejs.org/api/

언급URL : https://stackoverflow.com/questions/57875564/vuex-how-to-update-component-data-or-call-component-methods-from-store

반응형