Vuex 如何在安装时访问组件上的状态数据?

Vuex how to Access state data on component when it's mounted?

我正在尝试在使用 mounted() 挂钩加载组件后创建一个 Quill.js 编辑器实例。但是,我需要使用 Quill.setContents() 在同一个 mounted() 挂钩上使用我从 vuex.store.state 收到的数据来设置 Quill 的内容

我的麻烦在于,每当我尝试访问组件 returns 状态数据时,它的值为空,无论是在 mounted() 还是 created() 钩子。我也尝试过使用吸气剂和计算属性。似乎没有任何效果。

我已经包含了我的 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>

顺便说一句,作为最后的手段,我已经尝试了 props 选项。但是,无论如何它都没有帮助我。对不起,如果这个问题太长。感谢您花时间阅读本文。祝你有美好的一天 ;)

我会推荐以下步骤来调试上面的代码:

  • 在 Vue 开发工具中,检查网络调用后是否设置了状态
  • 当您尝试异步获取数据时,调用 created/mounted 挂钩时可能数据尚未到达。
  • 在您的组件中添加一个 updated 挂钩并尝试记录或访问状态,您应该能够看到它。

请提供以上调试的结果,我会添加更多细节。