1 安装vuex
#进入项目目录
npm i vuex@4
安装后,查看package.json
2 实现一个最简单的vuex 例子。
2.1 storer 的配置
//创建 src/store/store.ts
//不多,直接写这里,多的化,自建模块
import {createStore} from "vuex";
//定义结构
interface State {
count:number
}
export const store = createStore<State>({
//数据
state() {
return {
count:0
}
},
//方法。
mutations:{
incr(state) {
state.count ++
}
}
})
// 1 定义这里,会改 state 和 mutations 即可。
// 2 interface 这里定义结构,也可以省略.
2.2 写一个示例组件调用 store。
//src/page_demo/DemoStore.vue
<template>
<!--这里展示模版 内容-->
这里是使用store 的示例 <br/>
<h2>{{count}}</h2>
<button @click="incr"> + 1 </button>
</template>
<script setup lang="ts">
import {ref,computed} from "vue";
import {useStore} from 'vuex'
const store = useStore();
const count = computed(()=>{
//读store 的数据 。
return store.state.count;
})
const incr = () => {
//调sotre的方法。
store.commit('incr');
}
</script>
<style lang="scss" scoped>
</style>
2.3 在app.vue 中进行调用 .
<script setup lang = 'ts'>
...
import DemoStore from "./page_demo/DemoStore.vue
...
</script>
<template>
...
<demo-store></demo-store>
...
</template>
2.4 在其它组件内,读取vuex 的数据。
//src/page_demo/A.vue
<template>
<!--这里展示模版 内容-->
这里是A.vue 的内容
<h2> a.vue内容 {{count}}</h2>
</template>
<script setup lang="ts">
import {ref,computed} from "vue";
import {useStore} from 'vuex'
const store = useStore();
const count = computed(()=>{
return store.state.count;
})
</script>
<style lang="scss" scoped>
</style>
实际效果
总结: 使用vuex 可以让多个组件使用共享数据。 最简单的使用:
- 定义时会配置 state 和 mutations
- 使用时, 读 store.count, 和调用 store.commit('incr'); 即可。
- 当规模变大时就模块化
- 还有些其它的钩子,有需求时再折腾