Vuex集成
Vuex结合Composition API
组合式api中没有this.$store,可以使用useStore来替代
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
}
}
获取state和getters
// 定义store中的state和getters
const store = new createStore({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
// 在Composition API中获取state和getters
import { computed } from 'vue'
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
return {
// access a state in computed function
count: computed(() => store.state.count),
// access a getter in computed function
double: computed(() => store.getters.double)
}
}
}
获取Mutations and Actions
// 在Composition API中获取Mutations and Actions
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
return {
// access a mutation
increment: () => store.commit('increment'),
// access an action
asyncIncrement: () => store.dispatch('asyncIncrement')
}
}
}
Vuex集成TS结合Vuex
声明模块扩充
import { ComponentCustomProperties } from 'vue'
import { createStore,Store } from 'vuex'
//配置让Vuex支持ts 所有属性必须实现state接口
declare module '@vue/runtime-core' {
//declare your own store states
interface State {
count: number,
list:string[]
}
// provide typings for `this.$store`
interface ComponentCustomProperties {
$store: Store<State>
}
}
const store = createStore({
state () {
return {
count: 1,
list:['a','b','c']
}
},
mutations: {
increment (state:any):void {
state.count++
}
}
})
export default store;
main.ts中进行挂载
import { createApp } from 'vue'
import App from './App.vue'
import route from './routes'
import store from './vuex/store'
let app=createApp(App);
//挂载路由
app.use(route)
//挂载vuex
app.use(store)
app.mount('#app')
组件中进行挂载
<template>
<div>修改新闻--{{ count }}</div>
<br />
<ul>
<li v-for="(item, index) in list" :key="index">{{ item }}</li>
</ul>
<br />
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { mapState } from "vuex";
export default defineComponent({
data() {
return {};
},
methods: {},
computed: {
mylist():string[]{
return this.$store.state.list
},
...mapState({
count: (state:any) => state.count,
list: (state:any) => state.list,
})
},
});
</script>