vue3中vuex 的使用基本使用和二次封装
vuex技术
1.vuex简介和需求说明
- vuex可以帮助我们完成组件之间的数据传递,比如,一个组件里的按钮需要控制另一个组件的数据或者控件的时候,可以用到vuex来传递数据。
- 在 Vue.js 的项目中,如果项目结构简单, 父子组件之间的数据传递可以使用 props 或者 $emit 等方式,详细点击这篇文章查看。但是如果是大型项目,很多时候都需要在子组件之间传递数据,使用之前的方式就不太方便。Vue 的状态管理工具 Vuex 完美的解决了这个问题。
2.下载vuex
npm install vuex@next --save
yarn add vuex@next --save
3.新建vuex配置文件
- 在src目录下新建目录命名为store,在store目录下新建index.js文件,写入如下配置。
//index.js
import {createStore} from "vuex";
const $store = createStore({
//state可以看作是全局公共的数据,需要的组件可以调用
state: {
count: 0,
},
getters: {},
//mutations可以看作是调用state的事件,在组件中可以通过commit方法调用和响应
mutations: {
increment(state, payload) {
state.count = state.count + 1
console.log('payload:' + payload)
},
},
actions: {},
modules: {}
})
export default $store;
4.导入配置文件
- 在main.js中导入刚刚写好的文件
//main.js
import $store from '@/store';
app.use($store);
5.用例
5.在需要使用的组件同样写入
//组件
import $store from '@/store';
就可以开始使用了
//组件
<template>
<div>
//数据从store拿到,可以理解为全局数据
<div>{{ $store.state.count }}</div>
<el-button type="primary" @click="onStore">$store组件数据传递</el-button>
</div>
</template>
<script>
/* 方式三:*/
import {reactive, toRefs} from "vue";
import $store from "@/store";
export default {
name: "vuexDemo",
setup() {
const data = reactive({
})
const onStore = function () {
//这里触发了store/index.js里写入的increment事件
//payload回调为10
$store.commit('increment', 10)
console.log('$store.state.count:' + $store.state.count)
}
return {
...toRefs(data),
onStore
}
}
}
</script>
效果:这里点击button数字+1