vuex的基本使用

190 阅读3分钟

vuex

Vuex是什么

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

特点

  1. vue官方搭配,专属使用 (类似于:vue-router),有专门的调试工具
  2. 集中式管理数据状态方案 (操作更简洁)data() { return { 数据, 状态 }}
  3. 数据变化是可预测的 (响应式)

image.png

vuex就像是一个公共的大仓库,每个组件都可以去里面拿东西

Vuex中有5个重点

  1. state: 统一定义公共数据(类似于data(){return {a:1, b:2,xxxxxx}})
  2. mutations : 使用它来修改数据(类似于methods)
  3. getters: 类似于computed(计算属性,对现有的状态进行计算得到新的数据-------派生  )
  4. actions: 发起异步请求
  5. modules: 模块拆分

其中最为重要的内容是state和mutations

这里我就讲不用框架生成现成的vuex该怎么做

与router一样,当我们在项目中使用vuex之后,为了方便代码维护,我们一般需要做特殊的目录调整,约定的结构如下:

根组件
└── src
    ├── main.js
    ├── router
    │   └── index.js   # 路由
    └── store
        └── index.js   # vuex

我们写东西主要是在store文件下面的index.js里写

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state(){
    return {
      // 就是公共的数据,所有的组件都可以直接使用
      count: 100
    }
  }
})
export default store

向Vue实例注入store

在src/main.js中:

  1. 导入store
  2. 并注入Vue实例
// 省略其他
// 1. 导入store
import store from './store' 

new Vue({
  // 省略其他...
  store // 2. 注入Vue实例
})

这些配置基本和路由的配置差不多

Vuex-state定义公共数据并在组件中使用

上面已经给vue注入了灵魂,那我们马上开始使用vuex吧

定义公共数据

格式

const store = new Vuex.Store({
  state(){
    return {
      sum: '100',
      list:[
        { id: 100, name: "吃饭"},
        { id: 101, name: "睡觉" },
        { id: 102, name: "打豆豆"},
       ]
     }
    }
  }),

随便定义一些数据,state里面的格式和路由里的data一样

使用公共数据

格式:

在任意组件中,通过this.$store.state.属性名来访问。(在script标签使用)

在任意模板中,则可以省略this而直接写成: {{$store.state.属性名}}(在template标签使用)

浏览器扩展程序

谷歌浏览器记得安装一个扩展程序

image.png 装了这个后,在浏览器界面按F12

点vuex可以看到vuex的属性

image.png

Vuex-用mutations修改公共数据

image.png

数据在该在组件内部直接修改,虽然语法上不报错,也有响应式的特点。但是不推荐。特别是在严格模式下会报错。若将vue创建 store 的时候传入 strict: true, 开启严格模式,那么任何修改state的操作,只要不经过 mutation的函数,vue就会报错

const store = new Vuex.Store({
  state(){
      return {
        sum: '100',
        list:[
          { id: 100, name: "吃饭"},
          { id: 101, name: "睡觉" },
          { id: 102, name: "打豆豆"},
         ]
       }
      },
  mutations:{
      // 每一项都是一个函数,可以声明两个形参
      // 第一个形参state会自动捕捉同级的state
  	augment(state,形参) {
        state.sum++
      },
       subtract:function(state,形参 ) {
         state.sum--
       }
      }
  }),
  • mutations和state同级
  • 第一个参数是必须的,表示当前的state。在使用时不需要传入
  • 第二个参数是可选的,表示载荷,是可选的。在使用时要传入的数据

使用格式

this.$store.commit('mutation名', 实参)

Vuex-用getters的派生状态

在state中的数据的基础上,进一步对数据进行加工得到新数据。(与组件中computed一样)

定义格式

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state() {
    return {
      
    }
  },
  mutations: {
  },
  getters: {
      // state 就是上边定义的公共数据state
    getter的名字1: function(state) {
      return 要返回的值
    }
  }

})
export default store

使用格式

在组件中通过:$store.getters.getter的名字 来访问

Vuex-actions-发异步请求

actions介绍

  • actions是vuex的一个配置项

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

  • 特点:

    • action 内部可以发异步请求操作
    • action是间接修改state的:是通过调用 mutations来修改state
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state() {
    return {
      
    }
  },
  mutations: {
  },
  getters: {

  },
  actions: {
  async  getbook(context) {
      const res = await axios.get('接口地址')
      console.log(res);
      context.commit('mutations里定义的方法',res)
    }
  }

})
export default store

调用格式

在组件中通过this.$store.dispatch('actions的名字', 参数)来调用action

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

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

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

Vuex-用modules来拆分复杂业务

这个套娃是真恶心啊,我都不知道该怎么才能描述它了

modules的作用

拆分模块,把复杂的场景按模块来拆开

|--store /
|------- index.js # 引入模块
|------- modules
|-------------- / mod1.js # 模块1
|-------------- / mod2.js # 模块2

mod1.js文件设置

export default {
 // namespaced不写,默认为false,则在使用mutations时,不需要加模块名
 // namespaced为true,则在使用mutations时,就必须要加上模块名
  namespaced:true,
  state() {
    return {
      data: [{ id: 1, name: '电脑', price: 20000 },
      { id: 2, name: '手机', price: 10000 },
      { id: 3, name: '平板', price: 5000 }
      ]
  }
  },
  mutations: {
  
  },
  getters: {
   
  }
}

访问数据和修改数据的调整

  • 访问模块中的数据,要加上模块名
获取数据项:  {{$store.state.模块名.数据项名}}
获取getters: {{$store.getters['模块名/getters名']}}
  • 访问模块中的mutations/actions:
    • 如果namespaced为true,则需要额外去补充模块名
    • 如果namespaced为false,则不需要额外补充模块名
$store.commit('mutations名')        // namespaced为false
$store.commit('模块名/mutations名')  // namespaced为true

$store.dispatch('actions名')        // namespaced为false
$store.dispatch('模块名/actions名')  // namespaced为true

Snipaste_2022-05-12_17-22-21.png