Vuex模块装饰器语法
一、安装
- 由于Nuxt本身会根据store下面的文件自动添加Vuex(nuxt2包含vuex)
- 我们安装 vuex-module-decorators 即可
- 我当前使用的版本是
"vuex-module-decorators": "^2.0.0"
npm install vuex-module-decorators
# or
yarn add vuex-module-decorators
二、创建仓库
- 不用 创建index文件做创建仓库的操作
- 直接创建所需的仓库文件
例: mymodule.ts
import { Module, VuexModule, Mutation,Action } from 'vuex-module-decorators'
@Module({
name: 'mymodule', //名字与文件名保持一直
stateFactory: true,
namespaced: true
})
export default class MyModule extends VuexModule { //命名自己想要的模块名称 cart / user / ** /
// 直接创建state
wheels = 211
// 装饰器 创建修改state的方法
@Mutation
incrWheels(extra: number) {
this.wheels = extra
}
// getter 获取计算后的属性值
get axles() {
return this.wheels / 2
}
// 异步操作的装饰器
@Action
asyncFn(){
//异步操作...
}
}
三、在Vue的各种写法中使用
1.<script lang="ts">
<template>
<div>
<ul style="color: red">
<li>
{{ $store.state.mymodule.wheels }}
</li>
<li>
<button @click="handleChange">修改仓库值</button>
</li>
</ul>
</div>
</template>
<script lang="ts">
import {
onMounted,
useStore
} from '@nuxtjs/composition-api'
import { getModule } from 'vuex-module-decorators'
import MyModule from '~/store/mymodule'
export default defineComponent({
setup(props) {
const store = useStore()
const myMod = getModule(MyModule, store)
onMounted(() => {
console.log(store.state,myMod)
myMod.incrWheels(123000)
})
function handleChange() {
myMod.incrWheels(123)
}
return {handleChange}
}
})
</script>
2.vue-property-decorator
<template>
<div>{{ $store.state.mymodule.wheels }})</div>
<button @click="changeName">修改仓库值</button>
</template>
<script>
import { Component, Vue } from 'vue-property-decorator'
import { getModule } from 'vuex-module-decorators'
@Component({
layout: 'account'
})
export default class Login extends Vue {
mounted() {
// console.log('mounted', this.$store)
// let a = getModule(XuChengDong, this.$store)
// a.incrWheels('修改名字了')
}
changeName() {
getModule(MyModule, this.$store).incrWheels(111111)
}
}
</script>