vuex 的使用

vuex 的使用1 安装 vuex 依赖包 npm i vuex sava 2 导入 vuex 包 import Vuex from vuex 3 爆露出 store 对象 export const store new Vuex store state 存放的是全局共享的数据 state name xxx

大家好,我是讯享网,很高兴认识大家。

1.安装vuex依赖包

npm  i     vuex  --sava

2.导入vuex包

import       Vuex   from  'vuex'

3. 爆露出 store   对象

export   const store  =new   Vuex.store({

//state  存放的是全局共享的数据

state:{

name:"xxx" 

},

mutations:{

add(state){ //参数直接写state的参数

state.count++;//直接操作state中的数据

},

},

actions:{

},

getters(){})

4.   可以在main.js中全局引入

import  {store}  from "../store"

5.组件中访问State中 的数据的方式

(1)this.$store.state.全局数据名称;

举个例子:    在<template> <p> { {$store.state.name}} </p>  </template>//可以省略this哦

在方法中使用   this.$store.state.name

(2)import {mapState}  from     'vuex';//从vuex中按需引入  mapState函数

通过导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性

将全局数据,映射为当前组件的计算属性中

computed:{

...mapState(['count'])//使用展开运算符将全局state中的属性,数据映射进来

}

举个列子:<template> <p> { {count}} </p>  </template>//直接写成count,因为mapstate函数已经映射到组件的计算属性    computed中

6.使用 Mutation 来 变更store中的数据

A(1)只能通过mution 变更store数据,不可以直接操作store中的数据;

  (2)通过这种方式虽然操作起来比较繁琐,但是可以集中监控所有数据的变化;

  举个例子:  在   mutations:{

  add(state){

  state.count++

   }

  }

 在组件中的写入方法时用commit就可以把 mutations中的add()直接粘过来

btnclick(){

this.$store.commit("add)

}

(3)可以在触发mutations时传递参数

mutations:{


讯享网

adds(state,step){//变更状态(参1永远的state,参2外界传来的参数)

state.count+=step

}

}

通过调用commit函数   触发mutations时携带参数      this.$store.commit('add', 实参)

B 1.从vuex中按需导入  mapMutations 函数

import {mapMutations }from  'vuex'

将刚才导入的mapMutations  函数,将需要的mutations  函数,映射为当前组件的methods方法:

methods:{

...mapMutations(['add','adds'])//以对象的形式引入你需要使用的mutations中的方法;

btnclick(){

this.add()//就可以调用mutation中的   add()方法了

},

btnclick2(){

adds(){

this.adds(3)//代表传入的参数

}

}

}

7.actions用于处理异步任务

A如果通过异步操作变更数据,必须通过actions,不能使用mutations ,但是在action 中还要通过触发mutation的方式间接变更数据;

在actions中不能直接修改state的值,只能通过context.commit触发mutations中的函数

B  import {mapActions }from  'vuex'

methods:{

...mapActions(['addAsync'])//以对象的形式引入你需要使用的actions的方法

btnclick(){

this.addAsync()//直接调用actions中的addAsync

}

}

8.getter 用于对store中的数据进行加工处理形成新的数据

(1)getter可以对store中的已有数据加工处理之后形成新的数据,类似与vue中 的 computed属性;

(2)store中的数据发生变化,getter中的数据会跟随变化

getters(){

 showCount(state){

return  state.count}

}

使用getters

A  this.$store.getters. showCount

B   import {mapGetters }from  'vuex'

methods:{

...mapGetters (['showCount'])//以对象的形式引入你需要使用的actions的方法

}

<template> { { showCount}}  </template>

注意:在vuex中  不允许出现   this.$store.state.count++  这种写法直接在方法中直接改变全局变量;mutations中没有异步操作的代码;mapActions与mapMutations接受一个数组,主要实现将store中的方法直接映射到组件的methods中;

小讯
上一篇 2025-04-11 12:32
下一篇 2025-03-15 23:32

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/28559.html