programing

VueJ: 참조 방법컴포넌트 데이터 속성에 $store

itsource 2022. 10. 25. 21:57
반응형

VueJ: 참조 방법컴포넌트 데이터 속성에 $store

앱과 템플릿에서 Vuex 스토어 데이터를 사용하고 싶습니다.

내 VEUX 스토어:

var Vue = require('vue');
var Vuex = require('vuex');

Vue.use(Vuex)

let store = new Vuex.Store({
        state: {
            user: {},
        },
    }
}
module.exports = store

앱의 스토어 데이터를 사용하여 템플릿에 표시하고 싶습니다.단, 데이터 설정 시data소유물,this.$storeundefined. 단, 저는 이 파일에 액세스 할 수 있습니다.beforeRender기능:

var Vue = require('vue'),
store = require('../../link/to/my/store');

module.exports = {
    el: '#selector',

    store,

    components: {},

    data: {
        saving: false,
        user: this.$store.state.user // this.state is not available here
    },

    created: function(){},
    beforeCreate: function() {

        console.log(this.$state.state) // this.$state is available here

        // i get my data in the form of a json string from the dom
        // and update the global store with the data
        let user = document.querySelector('#user-data')
        if (user) this.$store.dispatch('updateUser', JSON.parse(user.innerHTML))

    },

    methods: {}

    }
};

나도 계산된 속성으로 시도했지만 소용이 없었다.

Vue 설명서에 따르면:

구성 요소를 정의할 때 데이터를 초기 데이터 개체를 반환하는 함수로 선언해야 합니다.

변경:

data: {
    saving: false,
    user: this.$store.state.user
},

다음과 같이 입력합니다.

data: function () {
  return {
    saving: false,
    user: this.$store.state.user
  };
}

그 다음에this함수에 대한 참조가 있을 것이다.$store.

언급URL : https://stackoverflow.com/questions/43661821/vuejs-how-to-reference-this-store-in-component-data-property

반응형