programing

VueJS - 마운트된 내부 저장 데이터 액세스

prostudy 2022. 3. 9. 10:37
반응형

VueJS - 마운트된 내부 저장 데이터 액세스

나는 다음 사항을 이해하는 데 어려움을 겪고 있다.

나는 a를 가지고 있다.store응용 프로그램에 필요한 변수가 포함되어 있는 경우.특히 a가 있다.globalCompanies다음 스토어:

globalCompanies: {
   current: [],
   all: [],
   currentName: "",
}

다른 구성 요소 내에서 다음 작업을 수행하십시오.

mounted() {
   this.$store.dispatch( "fetchUsers" );

   var currentName = this.$store.state.globalCompanies.currentName; 

   console.log(currentName); 
},

하지만, 이것은 그저 공허한 것으로 보여진다.나는 그 가치가 있다는 것을 안다. 왜냐하면 나는 그 가치가 있기 때문이다.computed그 답례로currentName그리고 그것은 보기 자체에서 잘 작동한다.장착 부품에 들어 있다는 사실이 마음에 들지 않을 뿐이다.

내가 어디에서 잘못되고 있으며 이 문제를 해결하기 위해 무엇을 할 수 있을까?실시간 이벤트를 위해 회사명을 캡처해야 해.

논의 결과:

Vuex 상태 값 질문에서 구성 요소의mounted후크, 이전에 해결되지 않는 비동기 작업에서 설정되었으므로 빈 값을 반환함mounted처형하다

Vuex에서 비동기 작업이 값으로 확인될 때 일부 기능을 트리거해야 하는 경우watchVuex 상태에서 값을 반환하는 계산된 속성.저장소의 값이 변경되면 계산된 속성은 이러한 변경사항을 반영하고watch수신기 실행:

const store = new Vuex.Store({
  state: {
    globalCompanies: {
      test: null
    }
  },
  mutations: {
    setMe: (state, payload) => {
      state.globalCompanies.test = payload
    }
  },
  actions: {
    pretendFetch: ({commit}) => {
      setTimeout(() => {
        commit('setMe', 'My text is here!')
      }, 300)
    }
  }
})

new Vue({
  el: '#app',
  store,
  computed: {
    cp: function() { // computed property will be updated when async call resolves
      return this.$store.state.globalCompanies.test;
    }
  },
  watch: { // watch changes here
    cp: function(newValue, oldValue) {
      // apply your logic here, e.g. invoke your listener function
      console.log('was: ', oldValue, ' now: ', newValue)
    }
  },
  mounted() {
    this.$store.dispatch('pretendFetch');
    // console.log(this.cp, this.$store.state.globalCompanies.test); // null
    // var cn = this.$store.state.globalCompanies.test; // null
    // console.log(cn) // null
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
<script src="https://unpkg.com/vuex@2.3.1"></script>
<div id="app">
  {{ cp }}
</div>

VueJS - 마운트된 내부 저장 데이터 액세스

이 문제에 부딪혔고, 그것은 범위 문제로 밝혀졌다.

저장:

export default () => {
     items:[],
     globalCompanies:{
        current:[],
        all:[],
        currentName: "Something"
     },
     ok: "Here you go"
}

게이터:

export default {
   getGlobalCompanies(state){
      return state.globalCompanies;
   }
}

장착됨:이건...

mounted() {
   // Initialize inside mounted to ensure store is within scope
   const { getters } = this.$store; 

   const thisWorks = () => {
      const globalCompanies = getters.getGlobalCompanies;
   }
},

불량: 마운트된 스코프 외부의 스토어에 도달

mounted() {
   function ThisDontWork() {
      const { getters } = this.$store; // this.$store == undefined
   }

   ThisDontWork();
},

참조URL: https://stackoverflow.com/questions/44324454/vuejs-accessing-store-data-inside-mounted

반응형