初次看到这个模块方式,感觉很是新奇,之前的vuex状态树使用方法用的也有些腻了,就想来实践一发新的东西
废话不多说,直接进入正题
Vuex状态树-模块方式官方文档解读
状态树还可以拆分成为模块,store 目录下的每个 .js 文件会被转换成为状态树指定命名的子模块
这句话啊,看了半天,我都没绕出来。之前一直用的是store目录下文件为:index.js、state.js、mutations.js、actions.js。后三个是index.js的子模块,你说这每个js文件都是一个模块?懵逼一分钟
继续往下:使用状态树模块化的方式,store/index.js 不需要返回 Vuex.Store 实例,而应该直接将 state、mutations 和 actions 暴露出来。 到这里我虽然还懵逼着,但是转念一想,nuxt还有这操作,都不用我们自己辛辛苦苦写export default store = () => new Vuex.Store({}) 了,倒也真的省事儿呢
还是继续看例子吧,官方给的这个,看了一遍没看懂(笨小孩的世界真滴难),你这index.js不是Vuex默认的store文件么,再来一todos.js,同样暴露出去的对象,不应该是index.js同级的么
重点来了,看不会不要紧,照猫画虎我还是会滴~
照猫画虎
// store/index.js
export const state = () => ({
num: 0
})export const mutations = {
increment (state) {
state.num ++
},
decrement (state) {
state.num --
}
}
// store/plus.js
export const state = () => ({
plusNum: 1
})
export const mutations = {
plus (state) {
state.plusNum ++
}
}
// store/minus.js
export const state = () => ({
minusNum: 10
})
export const mutations = {
minus (state) {
state.minusNum --
}
}
// pages/store.vue
<template>
<section class="container">
<table>
<tr>
<td colspan=4>vuex状态树使用</td>
</tr>
<tr>
<td>页内数据</td>
<td>index.js</td>
<td>plus.js</td>
<td>minus.js</td>
</tr>
<tr>
<td>{{ count }}</td>
<td>{{ $store.state.num }}</td>
<td>{{ $store.state.plus.plusNum }}</td>
<td>{{ $store.state.minus.minusNum }}</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</section>
</template>
跑一下,唷!报错了,我说同学们啊,我写的真的没有错!!!
好吧,报错内容:[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.










