programing

하위 구성 요소에서 Vuex가 작동하지 않음

kingscode 2022. 8. 18. 21:25
반응형

하위 구성 요소에서 Vuex가 작동하지 않음

일부 구성 요소와 루트 인스턴스 모두 vuex 개체에서 바인딩하는 대신 콘솔에 오류를 기록하기 때문에 다음과 같은 간단한 코드로 인해 많은 문제가 발생하고 있습니다.내가 여기서 뭘 놓칠 수 있지?

var state = {
	counter: 0
};
var mutations = {};
var store = new Vuex.Store({state, mutations});

var someComponent = Vue.extend({
  template: '<div>{{counter}}</div>',
  //data: function(){return {counter: 0}},
  vuex: {
    getters: {
      counter: getCounter
    }
  }
});

new Vue({
  el: '#app',
  components: {
  	'some-component': someComponent
  },
  store: store,
  vuex: {
  	getters: {
  		counter: getCounter
  	}
  }
});


function getCounter(state) {
  return state.counter;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>vue-bug</title>
  </head>
  <body>
    <div id="app">
    	<span>{{counter}}</span>
    	<some-component></some-component>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.0-rc.1/vue.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.0.0-rc.1/vuex.js"></script>
  </body>
</html>

제 코드로 Vue.use(Vuex)에 전화하고 있는데, 이 바이올린에서는 그럴 필요가 없습니다(Vuex는 이미 등록되어 있습니다).또, 데이터로의 라인 코멘트를 해제하면, 컴포넌트가 올바르게 렌더링 되는 것에 주의해 주세요.

어떤 도움이라도 대단히 감사합니다.

Vue/Vuex 2.0을 사용하는 경우 이 링크를 확인해야 합니다.vuex 2.0에서는 속성을 생성하지 않음vuexgetter와 액션을 설정할 수 있습니다.대신, 고객님의store.jsfile getters 객체를 정의하면 주에서 소품을 가져온 후 다음과 같이 스토어에 삽입할 수 있습니다.

const state = {
    counter: 0
}
const getters = {
    getCounter: state.counter
}

const actions = {}
const mutations = {}

export default new Vuex.Store({
    state,
    getters,
    actions,
    mutations,   
 })

컴포넌트에서는 다음과 같이 계산된 속성을 사용하여 getter를 정의할 수 있습니다.

import { mapGetter, mapActions } from 'vuex'

export default {
    template: '#some-template',
    computed: {
        yourFirstComputed() {},
        anotherOfYourComputed() {},
        ...mapGetters({
            getCounter: 'getCounter'
        })
    },
    methods: {
        yourMethod(){},
        ...mapActions({
             anyOfYourActions: 'anyOfYourActions'
        })
    }
}

그러면 이 소품들을 일반 계산에서처럼 부를 수 있습니다.반복하지만, 이 내용은 질문에 대한 댓글을 읽고 사용 중인 vuex 2에 적용됩니다.

도움이 됐으면 좋겠네요!

언급URL : https://stackoverflow.com/questions/39481929/vuex-not-working-in-child-component

반응형