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

时间:2017-03-26 04:48:44

标签: javascript vue.js vuejs2 vuex

我尝试使用 mounted()挂钩加载组件后创建一个Quill.js编辑器实例。但是,我需要使用与 vuex.store.state

我遇到的麻烦是,每当我尝试访问状态数据时,组件都会返回状态数据的空值,而不管是已挂载()还是已创建()挂钩。我也尝试过使用getter和计算属性。似乎没什么用。

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

顺便说一下,我已经尝试过道具选项作为最后的手段。但是,无论如何,它对我没有任何帮助。对不起,如果这个问题太长了。感谢您抽出宝贵时间阅读本文。祝你有愉快的一天;)

1 个答案:

答案 0 :(得分:1)

我将建议以下步骤来调试上面的代码:

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

请提供上述调试的结果,然后我就可以添加更多详细信息。