vuex 状态管理 入门

vuex是什么

是一个对 数据状态实现集中式管理 的工具。可以解决组件之间传递的问题

多组件共享状态(变量),有一个数据好多组件都用

组件数大于2,任何一个组件修改其他组件都要改变

实现组件通信

Store
每一个 Vuex 应用的核心就是 store(仓库)。“store” 基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。

使用

  1. 安装
npm install vuex
  1. 创建store/index.js
a. vuex
impote vuex form 'vuex'

b. 创建store对象
const store = new Vuex.Store({
    states:{
    //全局变量
    },
    
})
c. 导出store
    export dafault store
d. 在main.js中引入
    import store from "./store"
    new Vue({
        store
    })
基本使用
  1. 获取全局状态值 this.$store.state.xxxx
  2. 修改全局状态
    1. 同步:mutations
    2. 异步 先action 再mutation

五大属性

1.state 数据
  • 项目中共享的数据
 state:{
    name:'韩梅梅',
    age:'16',
    sex:0,
    phone:1231312313
  },
2.mutations : 同步方法
//修改state里数据的唯一途径
  mutations:{
    changeStateName(state,params){
      // state 全局状态数据
      //params 通过commit 触发传递的方法
      console.log('修改state数据',state,params)
      state.name=params.us     
    }
  }
   
this.$store.commit("")//触发mutations的某一个方法,第一个参数是名字  
3.actions :异步方法
  • 当vuex中出现异步,应该放到actions中,非必须
    • 可以将异步代码封装,统一管理异步
 // 异步存放的地方  请求成功后发起 commit 
  actions:{
    getNetName(context,params){
      console.log('触发actions',arguments)
      let {commit}=context
      setTimeout(()=>{
        let  name='来自星星的名字'
        commit('changeStateName',{us:name,ps:123})
      },500)
    }
  }

this.$store.dispatch("")  //发送一个请求,第二个参数是一个对象
4.getters : 派生属性
  • 对全局状态下的数据进行管理,类似于vue中的计算属性
  • 与state中数据进行关联,state数据改变,getter就会执行
  // 做数据的处理
  getters:{
    doubleName(state){
      return state.name+state.name 
    }
  }
5.modules : 模块化
  • state会被添加模块名字,其他的不会被加模块名
  • namespace:true 命名空间,防止不同的模块有相同的名字
moudles:{
    'a':{
        state:{name:"zhangsan"},
        getters:{}
    },
     'b':{
         state:{age:18}
     }
}
//不分模块写法:store.state.name
//分模块写法:store.a(模块名).state.name
a.js  b.js  在index.js中引用

import Vue from 'vue'
import Vuex from  'vuex'
Vue.use(Vuex)
import A from  './a'
import B from  './b'
let store = new Vuex.Store({
   modules:{A,B}
})

辅助函数

  • 值类型:state,getters

    可以通过辅助函数将值映射到内部的计算属性中

  • 函数类型:actions,mutation;

    通过辅助函数将函数映射到组件内部的方法里

映射:map ---------> mapState 、 mapGetters、 mapActions 、 mapMutations

使用

  • mapState
import {mapState} from "vuex"

export default{
    ...mapState(['name'])
}
//页面中的
this.$store.state.name
//可以写成
name
  • mapGetters
import {mapGetters} from "vuex"

export default{
    ...mapGetters(['name'])
}
//页面中的
this.$store.getters.name
//可以写成
name
  • mapMutations
import {mapMutations} from "vuex"

export default{
    ...mapMutations(['name'])
    changeName(){
        this.name({'name1'})
        //this.$store.commit('name')
    }
}
//页面中的
 this.$store.commit('name')
//可以写成
this.name('')
  • mapActions
import {mapActions} from "vuex"

export default{
    ...mapActions(['name'])
    changeName(){
        this.name({'name1'})
        //this.$store.dispatch('name')
    }
}
//页面中的
 this.$store.dispatch('name')
//可以写成
this.name('')

猜你喜欢

转载自www.cnblogs.com/zhaoxinran997/p/12374607.html