vuex详解

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。每一个Vuex 应用的核心就是 store(仓库)。store 基本上就是一个容器,它包含着你的应用中大部分的状态 ( state )。Vuex 的状态存储是响应式的,当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会被更新。改变 store 中的状态的唯一途径就是显式地提交(commit)mutation。这样可以方便地跟踪每一个状态的变化,从而使我们可以方便地跟踪每一个状态的变化

state

state是放置所有公共状态的属性,如果你有一个公共状态数据 , 你只需要定义在 state对象中

// 一、定义state
// 初始化vuex对象
const store = new Vuex.Store({
  state: {
    // 管理数据
    count: 0
  }
})

// 二、获取state
// 方法一
<div> state的数据:{{ $store.state.count }}</div>
// 方法二
// 把state中数据,定义在组件内的计算属性中
computed: {
  count () {
      return this.$store.state.count
  }
}
<div> state的数据:{{ count }}</div>
// 方法三
// mapState是辅助函数,帮助我们把store中的数据映射到 组件的计算属性中, 它属于一种方便用法
// 第一步导入mapState
import {mapState} from 'vuex'
// 第二步:采用数组形式引入state属性
mapState(['count'])
// 第三步:利用拓展运算符将导出的状态映射给计算属性
computed:{
  ...mapState(['count'])
}
<div> state的数据:{{ count }}</div>

mutation

state数据的修改只能通过mutations,并且mutations必须是同步更新,目的是形成数据快照

数据快照:一次mutation的执行,立刻得到一种视图状态,因为是立刻,所以必须是同步

// 一、定义mutations
const store  = new Vuex.Store({
  state: {
    count: 0
  },
  // 定义mutations,mutations是一个对象,对象中存放修改state的方法
 mutations: {
    // 方法里参数 第一个参数是当前store的state属性
    // payload 载荷 运输参数 调用mutaiions的时候 可以传递参数 传递载荷
    addCount (state) {
      state.count += 1
    }
  },
})

// 二、调用mutations
<template>
  <button @click="addCount">+1</button>
</template>

<script>
export default {
    methods: {
    //   调用方法
      addCount () {
         // 调用store中的mutations 提交给muations
        // commit('muations名称', 2)
        this.$store.commit('addCount', 10)  // 直接调用mutations
    }
  }
}
</script>

// 带参数的传递
addCount (state, payload) {
        state.count += payload
    }
this.$store.commit('addCount', 10)

// 辅助函数 mapMutations
import  { mapMutations } from 'vuex'
methods: {
    ...mapMutations(['addCount'])
}
// 上面代码的含义是将mutations的方法导入了methods中,等同于
methods: {
      // commit(方法名, 载荷参数)
      addCount () {
          this.$store.commit('addCount')
      }
}
// 此时可以直接调用
<button @click="addCount(100)">+100</button>

actions

state是存放数据的,mutations是同步更新数据,actions则负责进行异步操作

// 定义actions
 actions: {
  //  获取异步的数据 context表示当前的store的实例 可以通过 context.state 获取状态 也可以通过context.commit 来提交mutations, 也可以 context.diapatch调用其他的action
    getAsyncCount (context) {
      setTimeout(function(){
        // 一秒钟之后 要给一个数 去修改state
        context.commit('addCount', 123)
      }, 1000)
    }
 } 

// 原始调用
addAsyncCount () {
     this.$store.dispatch('getAsyncCount')
}
// 传参调用
addAsyncCount () {
     this.$store.dispatch('getAsyncCount', 123)
}
// 辅助函数  mapActions
import { mapActions } from 'vuex'
methods: {
    ...mapActions(['getAsyncCount'])
}
<button @click="getAsyncCount(111)">异步</button>

action是异步的,如何知道action何时结束?

通过让action返回Promise,在Promise的then中来处理完成后的操作

actions:{
  increment(context){
    return new Promise((resolve)=>{
      setTimeout(()=>{
        context.commit("increment")
      })
    })
  }
}

const store=useStore();
const increment=()=>{
  store.dispatch("increment").then(res=>{
    console.log(res,"异步完成")
  })
}

getters:某些属性需要经过变化后再使用,可以使用getters

// 定义getters
getters: {
    // getters函数的第一个参数是 state
    // 必须要有返回值
     filterList:  state =>  state.list.filter(item => item > 5)
}
// 原始方法调用getters
<div>{{ $store.getters.filterList }}</div>
// 辅助函数 mapGetters
computed: {
    ...mapGetters(['filterList'])
}
<div>{{ filterList }}</div>
mutations:{
  increment(state){
    state.counter++
  }
},
actions:{
  increment(context){
    context.commit("increment")
  }
}

module
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象,当应用变得非常复杂时,store对象就有可能变得相当臃肿,因此,vuex允许我们将store分割成模块,每个模块拥有自己的state、mutation、action、getter、甚至是嵌套子模块

// 模块化应用
const store  = new Vuex.Store({
  modules: {
    user: {
       state: {
         token: '12345'
       }
    },
    setting: {
      state: {
         name: 'Vuex实例'
      }
    }
  })

// 获取子模块的状态,需要通过 $store.state.模块名称.属性名来获取
<template>
  <div>
      <div>用户token {{ $store.state.user.token }}</div>
      <div>网站名称 {{ $store.state.setting.name }}</div>
  </div>
</template>

// 也可以使用getters来获取
getters: {
   token: state => state.user.token,
   name: state => state.setting.name
 }
computed: {
       ...mapGetters(['token', 'name'])
 }

// 模块化命名空间
user: {
       namespaced: true,
       state: {
         token: '12345'
       },
       mutations: {
        //  这里的state表示的是user的state
         updateToken (state) {
            state.token = 678910
         }
       }
    },
// 调用带命名空间的模块
// 方法一:直接调用-带上模块的属性名路径
test () {
   this.$store.dispatch('user/updateToken') // 直接调用方法
}
// 方法二:辅助函数-带上模块的属性名路径
methods: {
       ...mapMutations(['user/updateToken']),
       test () {
           this['user/updateToken']()
       }
   }
<button @click="test">修改token</button>

// 方法三:createNamespacedHelpers  创建基于某个命名空间辅助函数
import { mapGetters, createNamespacedHelpers } from 'vuex'
const { mapMutations } = createNamespacedHelpers('user')
<button @click="updateToken">修改token2</button>

vuex和localStorage的区别

1、vuex存储在内存中,而localStorage以文件的方式存储在本地,只能存储字符类型的数据,存储对象需要通过JSON.stringfiy和JSON.parse进行处理。

2、vuex用于组件之间传值,localStorage一般是在跨页面传递数据时使用,vuex能做到数据的响应式,localStorage不能

3、刷新页面时vuex存储的值会丢失,localStorage则不会

vuex的严格模式:在严格模式下,无论何时发生了状态变更且不是由mutation函数引起的,将会抛出错误。这能保证所有的状态更能被调试工具跟踪到

// 在vuex.store构造器选项中开启
const store=new Vuex.Store({
  strict:true
})
  • 13
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

温暖前端

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

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

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

打赏作者

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

抵扣说明:

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

余额充值