vue3.x+typescript的项目中使用vuex
dearweb
发布:2021-08-15 15:44:53阅读:
首先要在vue的项目中集成typescript,如果配置ts后调用this.$store有警告消息,请重启vscode,或者安装vue3.x的插件后重启编辑器,下面我们开始学习吧。
安装typescript
安装完了之后将store.js修改为stroe.ts
vue add typescript
配置store中的代码
vuex与typescript一起使用时必须声明自己的模块扩充
import { ComponentCustomProperties } from 'vue'
import { createStore,Store } from 'vuex'
// --- 让vue支持ts
declare module '@vue/runtime-core' {
interface State{
count:number,
list:string,
todos:string[]
}
interface ComponentCustomProperties {
$store:Store<State>
}
}
// -----上面这一段是增加的部分
const store = createStore({
state(){
return {
count:1,
list:'wuhan',
todos:['s','ww','ww']
}
},
mutations:{
increment(state:any){
state.count++
},
setCount(state:any,num:number){
state.count = num
}
},
getters:{
doneTodos:(state:any)=>{
return state.todos.filter((todos:any)=>todos.done)
}
},
actions:{
// 主要用于执行异步操作和mutations里面的方法
setContent(content){
setTimeout(()=>{
console.log(13)
content.commit('increment')
},2000)
//执行mutations里面的方法
}
}
})
export default store;下面是在模板文件中使用vuex
<template>
<div class='vuex'>
{{count}}
<hr>
{{$store}}
<br>
<button @click="setCount(10)">修改count的值(执行mutations方法)</button>
<br>
<hr>
{{num}}
<br>
<hr>
<button @click="actionsClick">出发actions方法</button>
</div>
</template>
<script lang="ts">
import {computed,defineComponent} from 'vue'
import { useStore } from 'vuex'
export default defineComponent({
name: 'vuex',
setup(){
const store = useStore()
return{
// // 获取state
count:computed(()=> store.state.count),
// 执行mutations方法
setCount:(e:any)=>{
store.commit('setCount',e)
},
//获取getter 方法
num:computed(()=>{
return store.getters.doneTodos
}),
//出发actions方法
actionsClick(){
store.dispatch('setContent')
}
}
},
})
</script>
<style lang='less' scoped>
</style>上面就是vuex在typescript使用的基本方法,你看懂了吗?可以私信小编喔!!
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧