programing

컴포넌트 마운트 시 Vuex의 상태 데이터에 액세스하는 방법

javaba 2022. 8. 12. 22:44
반응형

컴포넌트 마운트 시 Vuex의 상태 데이터에 액세스하는 방법

mounted() 훅을 사용하여 컴포넌트가 로드되면 Quill.js 에디터 인스턴스를 생성하려고 합니다.단, vuex.store.state에서 받은 데이터와 동일한 mounted() 후크에 Quill.setContents()를 사용하여 Quill의 콘텐츠를 설정해야 합니다.

여기서의 문제는 mounted() 또는 created() 훅에 관계없이 컴포넌트가 액세스하려고 할 때마다 상태 데이터의 빈 값을 반환한다는 것입니다.나는 getters와 computer properties를 사용해 보았다.아무것도 효과가 없는 것 같아요.

entry.js 파일을 첨부했고, 모든 컴포넌트를 연결했습니다.

Vue.component('test', {
    template: 
    `
        <div>
            <ul>
                <li v-for="note in this.$store.state.notes">
                    {{ note.title }}
                </li>
            </ul>
            {{ localnote }}
            <div id="testDiv"></div>
        </div>
    `,
    props: ['localnote'],
    data() {
        return {
            localScopeNote: this.localnote,
        }
    },
    created() {
        this.$store.dispatch('fetchNotes')
    },
    mounted() {
        // Dispatch action from store
        var quill = new Quill('#testDiv', {
            theme: 'snow'
        });
        // quill.setContents(JSON.parse(this.localnote.body));

    },
    methods: {
        setLocalCurrentNote(note) {
            console.log(note.title)
            return this.note = note;
        }
    }
});

const store = new Vuex.Store({
    state: {
        message: "",
        notes: [],
        currentNote: {}
    },
    mutations: {
        setNotes(state,data) {
            state.notes = data;
            // state.currentNote = state.notes[1];
        },
        setCurrentNote(state,note) {
            state.currentNote = note;
        }
    },
    actions: {
        fetchNotes(context) {
            axios.get('http://localhost/centaur/public/api/notes?notebook_id=1')
                    .then( function(res) {
                        context.commit('setNotes', res.data);
                        context.commit('setCurrentNote', res.data[0]);
                    });
        }
    },
    getters: {
        getCurrentNote(state) {
            return state.currentNote;
        }
    }
});

const app = new Vue({
    store
}).$mount('#app');

컴포넌트를 렌더링하는 index.html 파일은 다음과 같습니다.

<div id="app">
    <h1>Test</h1>
    <test :localnote="$store.state.currentNote"></test>
</div>

그나저나, 나는 마지막 수단으로 소품 옵션을 시도해 봤어.하지만 어쨌든 그것은 나에게 도움이 되지 않았다.질문이 너무 길었다면 죄송합니다.시간을 내어 읽어주셔서 감사합니다.좋은 하루 되세요;)

위의 코드를 디버깅하려면 다음 절차를 권장합니다.

  • Vue dev 도구에서 네트워크 호출 후 상태가 설정되는지 확인합니다.
  • 데이터를 비동기적으로 가져오려고 하면 다음과 같은 경우 데이터가 도착하지 않을 수 있습니다.created/mounted후크가 호출됩니다.
  • 를 추가합니다.updated컴포넌트에 접속하여 상태를 기록 또는 액세스하면 확인할 수 있습니다.

위의 디버깅 결과를 알려주시면 자세한 내용을 추가할 수 있습니다.

언급URL : https://stackoverflow.com/questions/43025118/vuex-how-to-access-state-data-on-component-when-its-mounted

반응형