【发布时间】: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