VueX的安装,核心概念与使用

VueX

安装vuex

image-20211031200945308

安装后项目会出现以下目录

image-20211031201056222

在store/index.js中,先引入 Vue 和 Vuex 并且别忘了 Vue.use(Vuex);

image-20211031201447047

当然你 Vuex 首先得跟 main.js 扯上点关系

image-20211031201648873

引入 store 文件 ,并且 Vue 实例上得将挂载 store

什么是VueX

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

例如:你有几个数据,几个操作,在多个组件上都需要使用,如果每个组件都去调用都是写,就会很麻烦,代码又臭又长。当然 如果没有大量的操作和数据需要在多个组件内使用的话呢,其实也就可以不用这个 Vuex了。

Vuex应用的核心就是 store(仓库)

“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)

我们可以先理解为vuex是帮我们存储数据的

说到存储数据,我们会想到哪里可以存储数据? 变量、数组、cookie、localstorage、session等等 。

那么store和这些有什么区别呢?

先看看store是长这样子的

image-20211031202109876

可以看到store对象里面包含了state,而state也是一个对象,所以"store”基本上就是一个容器。官方文档说明了:

Vuex 和单纯的全局对象有以下两点不同:

  1. Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。

  2. 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

Vue的核心是组件,组件需要进行通信,而父子组件之间的通信就是通过props和$emit,但是如果是非父子关系的组件想要进行通信,就需要运用到VueX

它把组件需要共享的东西提取出来,作为一个全局单例模式的管理,通过定义和管理状态管理中的各种概念并强制遵守一定的规则,使得代码结构化、易维护

store保存的数据

1.组件的初始数据

2.后台返回来的初始数据

VueX的核心概念

image-20211031203024171

state

先上例子

创建一个learning.vue

在App.vue中引入learning并引用

image-20211031203344326

在store/index.js的state对象中添加user对象

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

Vue.use(Vuex)

export default new Vuex.Store({
  //状态
  state: {
    user: {
      username: "zxl",
      password: "123456"
    }
  },
  //改变
  mutations: {
  },
  //行动
  actions: {
  },
  //模块
  modules: {
  }
})

在learning.vue中使用user

<template>
  <div id="learning">
    <h3>{{user.username}}</h3>
    <h3>{{user.password}}</h3>
  </div>
</template>

<script>
export default {
  name: "learning",
  computed: {
    user() {
      return this.$store.state.user
    }
  }
}
</script>

<style scoped>

</style>

由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性computed中返回某个状态

通过在根实例中注册 store 选项(main.js),该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。

当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // 箭头函数可使代码更简练
    count: state => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}

当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

computed: mapState([
  // 映射 this.count 为 store.state.count
  'count'
])
getters

getters 和 组件的 computed 类似,方便直接生成一些可以直接用的数据。当组装的数据要在多个页面使用时,就可以使用 getters 来做

getters 可以实时监听state值的变化(最新状态)

index.js

import Vue from 'vue'
import Vuex from 'vuex'
 
Vue.use(Vuex)
 
export default new Vuex.Store({
    state:{
        //存放组件之间共享的数据
        count: 2,
        other: 5,
    },
    getters:{
        //过滤state数据,function处理
        //监听state值的变化(最新状态)
        filter : state => state.count ? 1 : 0
    }
})

learning.vue

<template>
  <div id="learning">
    {{count}} ..{{num}} ..{{other}}   // 2 ..1 ..5
  </div>
</template>
 
<script>
    // 在单独构建的版本中辅助函数为 Vuex.mapState
    import { mapState } from 'vuex'
    export default{
        name: 'learning',
        computed:{
            count(){
                return this.$store.state.count
            },
            num(){
                return this.$store.getters.filter
            },
            ...mapState({
                // 使用对象展开运算符将此对象混入到外部对象中	 
                // 第一种:箭头函数可使代码更简练
                other: state => state.other
    			
                // 第二种: 传字符串参数 
                other: 'other'
 
                // 这里如果想得到num的值,是不能用state.num,因为没在state里定义
                // 那么如果用箭头函数的话也不可以,因为箭头函数改变了this的指向
                // 为了能够使用this获取局部状态,必须使用常规函数
                other(){
                     return this.num
                }
            })
        }
    }
</script>

getters对象中,使用mapGetters 辅助函数是将 store 中的 getter 映射到局部计算属性:

index.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  //状态
  state: {
    user: {
      username: "zxl",
      password: "123456"
    },
    user_extend: {
      sex: "男",
      age: "18",
      address: [
          "深圳","广州"
      ]
    },
    access_token: "asdfghjkl",
    refresh_token: "zxcvbnm"
  },
  getters: {
    user: state => state.user,
    username: state => state.user.username,
    password: state => state.user.password,
    user_extend: state => state.user_extend,
    sex: state => state.user_extend.sex,
    age: state => state.user_extend.age,
    address: state => state.user_extend.address,
    access_token: state => state.access_token,
    refresh_token: state => state.refresh_token
  },
  //改变
  mutations: {
  },
  //行动
  actions: {
  },
  //模块
  modules: {
  }
})

learning.vue

<template>
  <div id="learning">
    <h3>{{user.username}}</h3>
    <h3>{{user.password}}</h3>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  name: "learning",
  computed: {
    /*user() {
      return this.$store.getters.user
    }*/
    ...mapGetters(['user','user_extend','access_token','refresh_token'])
  },
  methods: {
  }
}
</script>

<style scoped>

</style>
mutations

在Java中有getter和setter方法,在vuex中,getters相当于java的getter方法的集合,mutations就相当于setter方法的集合,getters说白了就是用于查询,mutations对象就是用于修改

由于mutations中的方法相对于对方法里的数据写死,使得方法中的数据相当于常量,所以我们通常把mutations中的方法名全部写为大写英文字母

通过this. s t o r e . c o m m i t 方 法 , t h i s . store.commit方法,this. store.committhis.store.commit(“mutations中的方法名”,“方法中非state参数的新的参数值”)

上案例:

index.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  //状态
  state: {
    user: {
      username: "zxl",
      password: "123456"
    },
    user_extend: {
      sex: "男",
      age: "18",
      address: [
          "深圳","广州"
      ]
    },
    access_token: "asdfghjkl",
    refresh_token: "zxcvbnm"
  },
  getters: {
    user: state => state.user,
    username: state => state.user.username,
    password: state => state.user.password,
    user_extend: state => state.user_extend,
    sex: state => state.user_extend.sex,
    age: state => state.user_extend.age,
    address: state => state.user_extend.address,
    access_token: state => state.access_token,
    refresh_token: state => state.refresh_token
  },
  //改变
  mutations: {
    SET_USER(state,user) {
      state.user = user;
    },
    SET_USERNAME(state,username) {
      state.username = username;
    },
    SET_PASSWORD(state,password) {
      state.password = password;
    }
  },
  //行动
  actions: {

  },
  //模块
  modules: {
  }
})

learning.vue

<template>
  <div id="learning">
    <h3>{{user.username}}</h3>
    <h3>{{user.password}}</h3>
    <el-button @click="changePassword">修改密码</el-button>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  name: "learning",
  computed: {
    /*user() {
      return this.$store.getters.user
    }*/
    ...mapGetters(['user','user_extend','access_token','refresh_token'])
  },
  methods: {
    changePassword(){
      this.$store.commit("SET_PASSWORD","zxlzxl")
    }
  }
}
</script>

<style scoped>

</style>
action

分发 Action

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。

Action 通过 store.dispatch 方法触发:

store.dispatch('increment')

乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

Actions 支持同样的载荷方式和对象方式进行分发:

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

组合action,实现登录案例:

index.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  //状态
  state: {
    user: {},
    user_extend: {},
    access_token: "",
    refresh_token: ""
  },
  getters: {
    user: state => state.user,
    username: state => state.user.username,
    password: state => state.user.password,
    user_extend: state => state.user_extend,
    sex: state => state.user_extend.sex,
    age: state => state.user_extend.age,
    address: state => state.user_extend.address,
    access_token: state => state.access_token,
    refresh_token: state => state.refresh_token
  },
  //改变
  mutations: {
    SET_USER(state,user) {
      state.user = user;
    },
    SET_USERNAME(state,username) {
      state.username = username;
    },
    SET_PASSWORD(state,password) {
      state.password = password;
    },
    SET_USER_EXTEND(state,user_extend) {
      state.user_extend = user_extend;
    },
    SET_SEX(state,sex) {
      state.sex = sex;
    },
    SET_AGE(state,age) {
      state.age = age;
    },
    SET_ADDRESS(state,address) {
      state.address = address;
    },
    SET_ACCESS_TOKEN(state,access_token) {
      state.access_token = access_token;
    },
    SET_REFRESH_TOKEN(state,refresh_token) {
      state.refresh_token = refresh_token;
    }
  },
  //行动
  actions: {
    login({commit},user) {
      return new Promise((resolve) => {
        console.log(user)
        setTimeout(() => {
          let user = {
            username: "zxl",
            password: "123456"
          }
          let user_extend = {
            sex: "男",
            age: "18",
            address: [
              "深圳","广州"
            ]
          }
          let acces_token = "asdfghjkl"
          let refresh_token = "zxcvbnm"
          commit('SET_USER',user)
          commit('SET_USER_EXTEND',user_extend)
          commit('SET_ACCESS_TOKEN',acces_token)
          commit('SET_REFRESH_TOKEN',refresh_token)
          resolve()
        }, 1000)
      })
    }
  },
  //模块
  modules: {
  }
})

learning.vue

<template>
  <div id="learning">
    <h3>{{user.username}}</h3>
    <h3>{{user.password}}</h3>
    <el-button @click="changePassword">修改密码</el-button>
    <el-button @click="login">登录</el-button>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  name: "learning",
  computed: {
    /*user() {
      return this.$store.getters.user
    }*/
    ...mapGetters(['user','user_extend','access_token','refresh_token'])
  },
  methods: {
    changePassword(){
      this.$store.commit("SET_PASSWORD","zxlzxl")
    },
    login() {
      this.$store.dispatch("login",this.user)
    }
  }
}
</script>

<style scoped>

</style>
modules

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZXLzhuzhu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值