【问题标题】:Vuex how to Access state data on component when it's mounted?Vuex如何在安装时访问组件的状态数据?
【发布时间】:2017-08-18 21:41:50
【问题描述】:

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

我的问题是每当我尝试访问组件时,它都会返回状态数据的空值,无论是在 mounted() 还是 created() 挂钩上.我也尝试过使用 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>

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

【问题讨论】:

  • 我不明白你为什么要让 prop 变回状态?即数据方法。我说的是这一行localScopeNote: this.localnote,我认为这应该是一个计算属性

标签: javascript vue.js vuejs2 vuex


【解决方案1】:

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

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

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

【讨论】:

  • 这非常适合创建 Quill 编辑器和使用状态变量设置编辑器的内容。我错过了 updated() 钩子。非常感谢。
猜你喜欢
  • 2017-08-18
  • 2023-03-28
  • 2017-12-05
  • 2023-03-10
  • 1970-01-01
  • 2021-09-23
  • 2021-03-16
  • 1970-01-01
  • 2020-07-28
相关资源
最近更新 更多