gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:13:29 25 4
gpt4 key购买 nike

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

我的问题是,每当我尝试访问状态数据时,组件都会为状态数据返回空值,无论是在 mounted() 还是 created() Hook 上.我也尝试过使用 setter/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 选项。但是,无论如何它都没有帮助我。对不起,如果这个问题太长。感谢您花时间阅读本文。祝你有美好的一天 ;)

最佳答案

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

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

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

关于javascript - Vuex 如何在安装时访问组件上的状态数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43025118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com