Vue全家桶之Vuex

98 阅读3分钟

Vuex基础知识

  1. 定义: Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式, 采用集中式存储管理应用的所有组件的状态,解决多组件数据通信。

  2. 作用: 能够方便、高效地实现组件之间的数据共享

  3. 好处:

    • 数据的存储一步到位
    • 数据的流动非常清晰
    • Vuex的数据是响应式的
  4. 使用场景: 大型项目

image.png

在Vue项目使用Vuex

情况1:在老项目中使用。 先额外安装vuex包,然后在配置。

情况2:在新项目中使用。 在配置vue-cli中创建项目时,就可以直接选中vuex项,这样就不用做任何配置了(脚手架会自动帮我们完成的。

在脚手架工具中选中vuex.gif

这里只说明第1种情况

1. 配置Vuex

  1. 安装安装 Vuex 的依赖包, 命令: npm i vuex@3.6.2

  2. src文件夹目录下创建store/index.js文件

  3. store/index.js文件 导入,配置

// 1, 导入vue
import Vue from 'vue'
// 2, 导入vuex
import Vuex from 'vuex'
// 3, 将vuex配置为vue的插件
Vue.use(Vuex)
//4,  实例化Vuex
const store = new Vuex.Store({})

//5,  向外导出store 对象
export default store 

  1. main.js文件里面导入index.js文件并挂载到Vue实例上

//1.  导入store 文件夹下面的index.js
import store from '@/store/index.js'  // 可以简写为import store from '@/store'

//2.  将 store 对象挂载到 Vue 实例上
new Vue({
  render: h => h(App),
  store
}).$mount('#app')

2. state的基本使用

  1. 作用 : 存放全局共享的数据

  2. 使用方法:

  • 定义数据
new Vuex.store({
  state:{
      属性名: 属性值 
     }
})

示例:

state:{
    count:0,
    age:18,
    list:[
      {id:1, name:'吃饭',isDone:false},
      {id:2, name:'睡觉',isDone:false},
      {id:3, name:'打豆豆',isDone:false},
    ]
  },
  • 使用公共数据 格式:

在组件中,通过this.$store.state.属性名来访问。

在模板中,则可以省略this而直接写成: {{$store.state.属性名}}

<template>
  <div class="left-container">
    <p>count值:{{$store.state.count}}</p>
    <p>age值:{{$store.state.age}}</p>
    
    </div>
</template>

image.png

小结

state的作用是:保存公共数据(多组件中共用的数据)

state是响应式的: 如果修改了数据,相应的在视图上的值也会变化。

3.mutations基本使用

  1. 作用: 修改定义在state中的公共数据
  2. 使用方法:
  • 在 Vuex 中定义 Mutation 方法
mutations:{
    //mutations里面的函数,必须要有一个形参 
    addAge(state,payload){
      // console.log('add函数被调用了')
      // console.log(state);  state对象
      // console.log(payload);  传入的数据
      state.name=payload.uname
    },
    }

注意:

-   第一个参数是必须的,表示当前的state。在使用时不需要传入

-   第二个参数是可选的,表示载荷,是可选的。在使用时要传入的数据
  • 在组件中调用 Mutation 方法
<template>
 <button class="btn btn-primary" @click="fn">修改名字成小花</button>
</template>

<script>
export default {
  
  methods: {
    fn() {
      this.$store.commit('addAge', {uname:'小花'})
    },
    
      },
}
</script>

image.png

  1. 原理

image.png

注意: mutation 必须是同步函数

在项目开发中,为了保证 Store 中状态的每一次变化都是可追踪的,Vuex 规定: Mutation 必须是同步函数

。否则,vue-devtools 将无法正常追踪 Store 中数据的变化,这对大型项目的开发调试是灾难性的!

image.png

4. actions基本使用

  1. 作用: 发异步请求获取数据,调用mutations来保存数据,将整个ajax操作封装到Vuex的内部。

image.png

  1. 要点:
  • action 内部可以发异步请求操作
  • action是间接修改state的:是通过调用 mutation来修改state
  1. 使用方法
  • 定义action方法
actions:{
    asyncSubAge(context){
      console.log(context);//{getters: {…}, state: {…}, rootGetters: {…}, dispatch: ƒ, commit: ƒ, …}
      setTimeout(() => {
        context.commit('subAge') //调用mutation里面的subAge函数
      }, 1000);
    },
    asyncSubAgeN(context, playload){
      console.log(playload); //{num: 2}
      setTimeout(() => {
        context.commit('MinusAge',playload) //调用mutation里面的MinusAge函数
      }, 1000);
    }

  },
  • 调用action方法
<template>
 <button class="btn btn-danger" @click="actionFn">访问action里面的函数</button>
     <button class="btn btn-danger" @click="actionFnn">异步减N</button>
</template>

<script>
export default {
  
  methods: {
   actionFn(){
      this.$store.dispatch('asyncSubAge')
    },
    actionFnn(){
      this.$store.dispatch('asyncSubAgeN',{num:2})
    
      },
}
</script>

image.png

小结:

action一般用来发异步请求,数据回来之后,在去调用mutations来保存数据

image.png

将ajax请求放在actions中有两个好处:

  1. 代码得到了进一步封装。将发ajax和保存数据到vuex绑定在一起。
  2. 逻辑更通顺。如果数据需要保存在Vuex的state中,那从接口处获取数据的操作就定义在Vuex的actions中。

5. getters基本使用

  1. 作用: 它是 Vuex 中的计算属性,当 Store 数据源发生变化时,Getter 的返回值会自动更新

image.png

  1. 使用方法
  • 定义方法

const store = new Vuex.Store({
state:{
      list:[
      {id:1, name:'吃饭',isDone:false},
      {id:2, name:'睡觉',isDone:false},
      {id:3, name:'打豆豆',isDone:false},
    ]
  },
  
getters:{
    isAllDone(state){
return state.list.every(item=>item.isDone)
    }
  }  
  
  })
  • 在组件中使用方法
<template>
    <div>
    所有任务的状态: {{$store.getters.isAllDone}}
    </div>
</template>    

Vuex-state-mutation-getters 小结

vuex维护公共数据,主要有两个动作:

  1. 定义数据:
  2. 提供获取/修改数据的方法

image.png

6. module基本使用

  1. 作用: Vuex 中的 Module 表示按照模块化的开发思想,把不同的数据和方法,按照彼此的关联关系进行封装。

image.png

  1. 使用方法
  • store文件夹下面新建一个module/count.js文件定义模块
export default {
namespaced:true,//开启命名空间 
//state必须是一个函数
  state() {
    return {
      list:[
        {id:1, name:'吃饭',isDone:false},
        {id:2, name:'睡觉',isDone:false},
        {id:3, name:'打豆豆',isDone:false},
      ]
    };
  },
  mutations:{},
  action:{},
  getters:{}
  }
  • index.js文件里面导入模块并注入到实例化Store对象中
//导入module文件夹下面的count.js
import count from './module/count'


const store = new Vuex.Store({
  modules:{
    count1:count, //模块名:数据名
    todo
  }
  
})
  • 访问模块里面的成员

未开始命名空间时, 使用$store.state.模块名.数据名访问

开启命名空间时, 使用计算属性 computed:{...mapState('模块名', ['state里面的数据'])}访问

<template>
    <div>
    <p>{{$store.state.模块名.数据名}}</p> //未开启命名空间可以使用$store.state.模块名.数据名 访问,开启命名空间之后,需要通过辅助函数来访问state里面的数据
    
    <button @click="asyncFn">触发模块里面的actions</button>
    </div>
</template> 

<script>

import {mapState} from'vuex'

export default {
  computed: {
  //开启命名空间之后的访问方法 ...mapState('模块名', ['state里面的数据']),
   ...mapState('count1', ['count']),
    }
  },

}

</script>

7. vuex辅助函数

  1. 辅助函数总共有4个: mapState, mapMutations, mapActions,mapGetters,其作用和对应的State,Mutations,Actions,Getters一致

  2. 使用方法

  • 组件里面导入函数

<script>
import {mapState, mapMutations, mapActions,mapGetters} from'vuex'

export default {
  computed: {
   ...mapState('count1', ['count']),
   ...mapGetters('count1', ['getAccount']),
  },
  methods: {
   ...mapMutations('count1',['addCount']),
   ...mapActions('count1',['asyncFn']),
   //调用对应的函数
   fn(){
   this.addCount()
   },
    fnn(){
   this.getAccount()
   },
  },

}

</script>
  • 模板里面使用
<template>
 <div>
  <p>{{ count }}</p>
<p>{{ getAccount }}</p>
 </div>
</template>

map函数用法汇总

image.png

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第2天,点击查看活动详情