安装
npm install vuex@版本号
//vuex的版本号根据你选择的vue.js的版本来确定(这个在之前的文章里面有)
使用
安装完之后你需要在创建一个vuex实例如:
//首先导入
import Vue from 'vue'
import Vuex from 'vuex'
//在进行使用
vue.use(Vuex),
//然后创建vuex实例
const store = new Vuex.Store({
// state 中存放的就是全局共享的数据
state:{ COUNT:0}
})
//然后在挂载到app上
const app = createApp({ /* 根组件 */ })
// 将 store 实例作为插件安装
app.use(store)
1.State
state相当于一个共享的存储器,每个组件都可以从state中获取共享的信息(这是我自己的理解,如果有错误,请大佬指出)
组件访问state的第一种方式就是通过
this.$store.state.count //this.$store.state.全局数据名称
组件访问state的第二种方式就是
//在组件中导入mapstate
import {mapState} from 'vuex'
//在组件的计算属性中声明,然后就可以直接在组建中调用count
...mapState(['count'])
{{count}} //插值表达式中直接使用
2.Mutations
1.组件修改state中的数据时需要用到Mutations,当然这个Mutations下面只能进行同步操作的修改
2.而且只有Mutations中能对state中的数据进行修改
//组件修改时通过
this.$store.commit('mutations里面的函数')
//定义 Mutation
const store = new Vuex.store({
state:{
count:0
},
mutations:{
add(state) {
//变更状态
state.count++
}
}
})
//触发mutation
methods:{
handle1(){
//触发mutations的第一种方式
this.$store.commit('add')
}
}
如触发带有参数
//定义Mutation
const store = new Vuex.store({
state:{
count:0
},
mutations:{
addN(state, step){
//变更状态
state.count +=step
}
}
})
//触发mutation
methods:{
handle2(){
//在调用 commit函数,
//触发mutations 时携带参数
this.$store.commit('addN',3)
}
}
mutations 的第二种触发方式
//1.vuex中按需导入mapMutations函数
import { mapMutations } from 'vuex'
//2.将指定的mutations函数,映射为当前组件的methods函数
methods:{
...mapMutations({'add',''})
}
之后再本组件中把add当函数使用即可
3.actions
在进行组件进行异步操作修改state中的数据时,需要用到actions
如果通过异步操作变更数据,必须通过action,而不能使用Mutation,但是Action中还是要通过触发Mutation的方式间接变更数据。
acitons:{
addAsync(context){
setTimeout(()=>{
context.commit('add')
},10000)
}
}
//触发action
methods:{
handle() {
//触发acitons的第一种方式
this.$store.dispatch('addAsync')
}
}
带有参数的触发方式
actions:{
addNAsync(context,step) {
setTimeout(()=> {
context.commit('addN',step)
},1000)
}
}
//触发action
methods:{
handle(){
//在调用dispatch函数,
//触发 actions 时携带参数
this.$store.dispatch('addNAsync',5)
}
}
actions的第二种触发方式
/1.从 vuex 中按需导入 mapAchtions函数
import { mapActions } from 'vuex'
//2.将指定的actions函数,映射为当前组件的methods函数
methods:{
...mapActions(['addASync',addNASync])
}
4.getters
相当于个state增添新的数据,但是不修改,可以对原有的数据进行包装
-
Getter可以对store中
-
store中数据发生变化,Getter的数据也会跟着变化
-
已有的数据加工处理之后形成新的数据,类似vue的计算属性
使用的第一种方式
this.$store.getters.名称
第二种方式
import {mapGetters} from 'vuex'
computed: {
...mapGetters(['showN'])
}
当然你需要首先再store中的getter中写好才可以调用
5.Module
Vuex 允许我们将 store 分割成模块。每个模块拥有自己的 state、mutation、action、getter、
比如将登录模块(user),和注册模块(register)的信息分开
//user模块 user.js
const user = {
state: () => ({ .... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
//register模块 register.js
const register = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
// 总store
const store ={
module:{
user, register
}
}
在组件中使用的时候就可以通过
this.$store.user.数据名称
this.$store.regisetr.数据名称
也可以
命名空间
这个问题详细请看vuex文档比较清除,命名也可以嵌套使用[acount/user]
以上就是vuex中的基础(欢迎各位大佬指正)