vuex使用详解,vuex模块化使用

vuex安装

方法1: 创建脚手架项目直接购选vuex
在这里插入图片描述
方法2: 使用命令行
vue2项目下载vuex3版本,vue3项目要安装vuex4版本

npm install vuex@3

vuex配置

在项目src目录创建store文件夹index.js

//引入vuex
import Vuex from 'vuex';
//引入vue
import Vue from 'vue'
Vue.use(Vuex)
//创建store 暴露出去
export default new Vuex.Store({
  //准备一个state-储存数据
  state: {
  },
  //准备一个getters-对state里面的数据做操作相当于computed
  getters: {
  },
  //准备一个actions-响应组件中的动作
  actions: {
  },
  //准备一个mutations-操作数据
  mutations: {
  },
  //vuex模块化
  modules:{

  }
})

main.js中引入
在这里插入图片描述

vuex使用简介

vuex主要用于全局状态共享,就是不同组件可以使用一个数据对数据进行增删改,组件进行对应更改。主要有五个属性:state,getters,mutations,actions,modules

1.state

和data类似在这里定义的数据可以在任意组件使用

export default new Vuex.Store({
  //准备一个state-储存数据
  state: {
     name:'章三',
     age:20
  },
})

方法1:直接使用 $store.state.name

 <h1>姓名:{{$store.state.name}}</h1>
 <h1>年龄:{{$store.state.age}}</h1>

方法2:计算属性 this.$store.state.name

<h1>姓名:{{name}}</h1>
computed:{
  name(){
    return this.$store.state.name
  }
}

方法3:借助vuex的mapState辅助函数

 import { mapState } from 'vuex'
<h1>姓名:{{name}}</h1>
<h1>年龄:{{age}}</h1>
computed:{
 //对象写法
 ...mapState({name:'name',age:'age'})
 //数组写法 key和value名字要保持一致也就是state定义的name和...mapState的['name']
 ...mapState(['name','age'])
}

2.mutations

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

例子:点击按钮让年龄增加10

export default new Vuex.Store({
  //准备一个state-储存数据
  state: {
    name:'张三',
    age:20
  },
  //准备一个mutations-操作数据
  mutations: {
    //增加年龄方法 value时接受的参数 
    //方法名建议大写与actions定义方法作区分
    ADDAGE(state,value){
      state.age += value
    }
  },
})

方法1:直接使用this.$store.commit(‘AddAge’,10)

 <h1>年龄:{{age}}</h1>
 <button @click="addAge">点击增加年龄</button>
  methods: {
    addAge(){
      this.$store.commit('ADDAGE',10)
    } 
 }

方法2:借助mapMutations辅助函数
在页面引入mapMutations

 import { mapMutations } from 'vuex'

对象方法 @click方法需要加()用来传递参数’addAge’这个对应mutations里面的ADDAGE方法

 <h1>年龄:{{age}}</h1>
 <button @click="addAge(10)">点击增加年龄</button>
  methods: {
  ...mapMutations({addAge:'ADDAGE'})
 }

数组方法与对象方法 类似更加便捷,等于直接在页面使用mutations里面的ADDAGE方法

 <h1>年龄:{{age}}</h1>
 <button @click="ADDAGE(10)">点击增加年龄</button>
  methods: {
  ...mapMutations(['ADDAGE'])
 }

3.actions

Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作。可以在此方法向后端发送请求,做后续操作。

例子:点击按钮3豪秒后让年龄增加10
先在actions和mutations里面写好方法

export default new Vuex.Store({
  //准备一个state-储存数据
  state: {
    name:'张三',
    age:20
  },
  //准备一个actions-响应组件中的动作
  actions: {
    waitadd(context,value){
       console.log('actions waitadd被调用了');
        setTimeout(() => {
         context.commit('WAITADD',value)
      }, 300);
    }
  },
  //准备一个mutations-操作数据
  mutations: {
    //增加年龄方法
    WAITADD(state,value){
        state.age += value
    }
  },
})

这里是需要调用actions定义的方法,再让actions去调用mutations,不能直接调用mutations里面的WAITADD
方法1:直接使用this.$store.dispatch(‘waitadd’,10)

 <h1>年龄:{{age}}</h1>
 <button @click="waitAdd">点击3豪秒后增加年龄</button>
  methods: {
    waitAdd(){
      this.$store.dispatch('waitadd',10)
    } 
 }

方法2:借助mapActions辅助函数
在页面引入mapActions

 import { mapActions } from 'vuex'

对象方法:相当于点击按钮调用的是actions里面的waitAdd方法

 <h1>年龄:{{age}}</h1>
 <button @click="personAdd(10)">点击3豪秒后增加年龄</button>
  methods: {
  //可以有多个方法
  ...mapActions({personAdd:'waitAdd',personName:'setName'})
 }

数组方法:跟对象方法一样不同的是这里要在@click直接使用waitadd

 <h1>年龄:{{age}}</h1>
 <button @click="waitadd(10)">点击3豪秒后增加年龄</button>
  methods: {
  ...mapActions(['waitadd'])
 }

4.getters

跟咱们常用的计算属性computed差不多作用,使用方法和state几乎一样就是名字不一样

例子:定义一个值比年龄大10倍

export default new Vuex.Store({
  //准备一个state-储存数据
  state: {
    name:'张三',
    age:20,
    bigAge:0
  },
  //准备一个getters-对state里面的数据做操作相当于computed
  getters: {
    bigAge(state){
      return state.age * 10
    }
  },
})

方法1:直接使用 $store.getters.bigAge

<h1>我比原来年龄大10倍:{{$store.getters.bigAge}}</h1>

方法2:计算属性 this.$store.getters.bigAge

<h1>我比原来年龄大10倍:{{bigAge}}</h1>
computed:{
  bigAge(){
    return this.$store.getters.bigAge
  }
}

方法3:借助vuex的mapGetters辅助函数

 import { mapGetters } from 'vuex'
<h1>我比原来年龄大10倍:{{bigAge}}</h1>
computed:{
 ...mapGetters(['bigAge'])
}

5.modules

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

可以理解为把store又分为多个模块,比如有订单模块,购物车模块不能把这几个模块的内容全部放在一个state里面。所以可以定义多个模块,方便不同程序猿对自己定义的数据进行操作和最终提交代码时减少一些麻烦。

modules模块化

首页先创建student.js,teacher.js然后在store->index.js引入。这边使用两个模块是为了区分不同的写法,student相关使用辅助函数mapState .mapGetters.mapMutations.mapActions,teacher相关不使用辅助函数。
在这里插入图片描述
index.js文件内容

//引入vuex
import Vuex from 'vuex';
//引入不同模块
import student from './student'
import teacher from './teacher'
//引入vue
import Vue from 'vue'
Vue.use(Vuex)
//创建store 暴露出去
export default new Vuex.Store({
  //vuex模块化
  modules: {
    student,teacher
  }
})

student.js和teacher.js文件内容基本一致,可以直接复制。

export default {
  //命名空间开启,默认关闭
  namespaced:true,
  state: {
    studentName:"张三",
    studentSix:'男',
    studentAge:18,
  },
  getters: {
    //比年龄大10倍
    bigAge(state){
      return state.studentAge * 10
    }
  },
  actions: {
    //异步执行3毫秒后年龄加1
    waitAdd(context,value){
      setTimeout(() => {
        context.commit('WAITADD',value)
      }, 300);
    }
  },
  mutations: {
    //点击年龄增加??value传递过来的参数
    ADDAGE(state,value){
      state.studentAge += value
    },
    WAITADD(state,value){
        state.studentAge +=1
    }
  },
  modules: {
  }
}

模块化state

方法1:辅助函数写法

   <h1>学生名字:{{studentName}}</h1>
   <h1>老师名字:{{teacherName}}</h1>
    computed: {
        //引入mapState里面不同的模块
        ...mapState('student', ['studentName', 'studentSix', 'studentAge']),
        ...mapState('teacher', ['teacherName']),
    },

方法2:非辅助函数写法

   <h1>学生名字:{{studentName}}</h1>
   <h1>老师名字:{{teacherName}}</h1>
    computed: {
       studentName(){
         return this.$store.state.seudent.studentName
      },
      teacherName(){
         return this.$store.state.teacher.teacherName
      }
    },

模块化mutations

方法1:辅助函数写法

   <button @click="ADDAGE(1)">点击按钮年龄加1</button>
    methods: {
        //数组方法 第一个参数为模块的名字这里为student
        ...mapMutations('student',['ADDAGE'])
    },

方法2:非辅助函数写法

   <button @click="addAge()">点击按钮年龄加2</button>
   methods: {
      addAge(){
         //不使用辅助函数需要指定模块下的某个方法 'teacher/ADDAGE'
         this.$store.commit('teacher/ADDAGE',2)
      },
   },

模块化actions

方法1:辅助函数写法

   <button @click="waitAdd(1)">点击按钮3毫秒年龄加1</button>
    methods: {
        //数组方法 第一个参数为模块的名字这里为student
        ...mapActions('student',['waitAdd'])
    },

方法2:非辅助函数写法

   <button @click="waitAdd()">点击按钮年龄加2</button>
   methods: {
      waitAdd(){
         //不使用辅助函数需要指定模块下的某个方法 'teacher/waitAdd'
         this.$store.dispatch('teacher/waitAdd',1)
      },
   },

模块化getters

方法1:辅助函数写法

   <h3>学生十倍之后的年龄:{{ bigAge }}</h3>
    computed: {
        //引入mapGetters里面不同的模块
        ...mapGetters('student',['bigAge'])
    },

方法2:非辅助函数写法

   <h3>老师十倍之后的年龄:{{ bigAge }}</h3>
   computed: {
      bigAge(){
         return this.$store.getters['teacher/bigAge']
      }
   },
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js是一个流行的JavaScript框架,它允许您构建动态Web应用程序。Vuex是一个专为Vue.js应用程序开发的状态管理模式。它允许您在应用程序中管理和维护状态,例如用户信息、购物车、主题等。Vuex将状态存储在一个集中的存储库中,称为storeVuex的核心概念包括state、mutations、actions和getters。 - state:存储应用程序级别的状态,可以通过store.state访问。 - mutations:用于更改状态的函数,必须是同步函数。可以通过store.commit方法调用。 - actions:用于处理异步操作的函数,可以包含任意异步操作。可以通过store.dispatch方法调用。 - getters:用于从store中获取状态的函数,可以通过store.getters访问。 下面是一个简单的示例,演示如何在Vue.js应用程序中使用Vuex: 1.安装Vuex ```shell npm install vuex --save ``` 2.创建store ```javascript import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { getCount: state => { return state.count } } }) export default store ``` 3.在Vue组件中使用store ```javascript <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </div> </template> <script> import { mapGetters, mapActions } from 'vuex' export default { computed: { ...mapGetters([ 'getCount' ]) }, methods: { ...mapActions([ 'increment', 'incrementAsync' ]) } } </script> ``` 在上面的示例中,我们创建了一个名为count的状态,并定义了一个名为increment的mutation和一个名为incrementAsync的action。我们还定义了一个名为getCount的getter,用于从store中获取count状态。在Vue组件中,我们使用mapGetters和mapActions帮助程序将getter和action映射到组件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值