关于Vuex的基本使用

1.vuex简介

Vuex是专门为Vue框架提供的。用来管理状态的模块。集中式管理状态数据。它管理的数据可以追踪变化。它是在多个组件之间共享数据的方案。

在store/index.js 定义仓库对象,需要对仓库对象进行配置

state:需要共享的数据

mutations:定义修改state的同步的方法

getters:定义对状态的过滤的操作,类似于组件的计算结果

actions:定义异步获取数据并且赋值给state

modules:状态模块化

2.vuex的定义

state:状态,需要共享的数据 不能直接修改,要么通过actions异步进行,要么通过mutations进行同步修改.

export default new Vuex.Store({
  state: {
    a:10,
    txt:"hello",
    arr:["yesterday once more","my heart will go on"],
    name:{
      firstName:"张",
      lastName:"三"
    },
    homeData:[]
  },
})

mutations:同步修改state的字段,里面都是一些函数,修改state字段里面的状态。

  mutations: {
    // 参数1state对象,参数2调用的时候传递的实参
    setNum(state,v){
      state.a = v
    },
    // 修改txt状态的函数
    setTxt(state,v){
      state.txt = v
    },
    setHomeData(state,v){
      state.homeData  = v
    }
  },

getters:类似于组件的计算结果,有返回值,过滤

  getters:{
    fullName(state){
      return state.name.firstName + state.name.lastName
    }
  },

actions: 异步获取数据并且通过同步修改的方法进行修改

actions: {
    // 参数1:仓库对象,参数2:可以传递一些参数
    queryData(store,v){
      return new Promise((resolve,reject)=>{
        axios.get("/api/test",{params:{page:1,pageSize:3}}).
        then(res=>{
          // 提交mutations方法,调用mutations中同步的方法
          store.commit("setHomeData",res.data.data)
          resolve()
        }).catch(err=>{
          reject(err)
        })
      })
    }
  },

3.vuex的使用

state:  

1.$store.state.字段

  <p>{{ $store.state.a }}</p>//store全局唯一的对象

2.先通过maoState进行映射到computed里面然后去使用

// 导入vuex的映射函数
import {mapState} from "vuex"
export default {
  computed:{
// 映射状态的时候可以在组件的计算结果中进行映射,通过扩展运算符把仓库的一个状态以数组的形式写在mapstate的参数里面
    ...mapState(["a","txt","arr"])
  }
}

mutations:

1.this.$store.commit("setNum",传递的数据)

export default {
  methods: {
    f1() {
      // 第三种方法 通过commit提交方法进行提交修改
      this.$store.commit("setNum", 1000000);
      this.$store.commit("setTxt", "撒谎比");
    },
  },

2.先通过mapMutations进行映射到methods里面然后再去使用

import {mapMutations} from "vuex";
export default {
  methods: {
// 把mutations里面的修改方法映射到methods,相当于在本组件的methods中添加一些函数,可以在本组件使用
    ...mapMutations(["setNum", "setTxt"]),
    f1() {
      // 第一种修改状态的方法
      // this.setNum(100)
      // this.setTxt("你好")
      // 第二种修改 通过仓库对象访问状态直接进行修改,不建议去使用
      // this.$store.state.a = 1000000
    },
  },

actions

1.this.$store.dispatch("action的名字",传递的数据)

export default {
  created(){
    // 仓库里面的异步 action调用
    this.$store.dispatch("queryData","123").then(res=>{
      console.log("数据请求成功");
    })
  },
  methods:{
    ...mapActions(["queryData"])
  }
}

2.先通过mapActions进行映射到methods里面然后再去使用

import {mapActions,mapGetters} from "vuex"
export default {
  created(){
    this.queryData()
  },
  methods:{
    ...mapActions(["queryData"])
  }
}

getters:

1.this.$store.getters("getter的名字",传递的数据)

  <p>{{$store.getters.getSkill}}访问根仓库的getters</p>

2.先通过mapGetters进行映射到computed里面然后再去使用

import { mapGetters } from "vuex";
export default {
  computed: {
    ...mapGetters(["fullName"]),
  },
};

4.vuex子仓库的配置

// 导出的对象和仓库index.js的配置字段是一样的
export default{
// 模块化的仓库state是一个函数,像子组件中的一样
    state(){
        return{
            count:1,
            books:[],
            todos:[
                {id:1,text:"睡觉",done:false},
                {id:2,text:"吃饭",done:true},
                {id:3,text:"打豆豆",done:false},
                {id:4,text:"敲代码",done:true}]
        }
    },
    mutations:{
        setCount(state,v){
            state.count = v
        },
        setBooks(state,v){
            state.books = v
        }
    },
    getters:{
        //  过滤未完成的事件
   umcomplete:(state,getters,rootState)=>{
   // state:本模块的数据
   // getters:仓库中所有的getters,包括根仓库种getters,如果添加了命名空间getters就是本模块的getters
   // rootState 根仓库的状态
            return state.todos.filter(v=>{
                return !v.done
            })
        },
        // 过滤出已经完成的
        done:(state,getters,rootState)=>{
            return state.todos.filter(v=>{
                return v.done
            })
        }
    },
actions:{
async getData(store,v){
var result = await axios.get("/myApi/lurker/carguide/getwar
ningmsg?city=zz&type=2")
//把数据存入books,利用setBooks
store.commit("setBooks",result.data.data.content)
        }
    },
    modules:{
    },
    // 使用命名空间,以后本模块的数据需要通过指定命名空间进行访问
    // 在index.js的modules字段配置当中给模块进行空间的命名
namespaced:true
}

注意:模块仓库设置namespaced:true意为允许设置模块名,可以在根仓库种进行设置模块子仓库的名字,方便后面使用。在根仓库设置模块仓库的名代码如下:

先对子仓库进行导入,命名为moduleA
import moduleA from "./module.js"
//在根仓库的modules中设置名为a  
modules: {
    a:moduleA
  }

5.使用子仓库

举例为根仓库下的a子仓库,在跟仓库命名为a

state

1 $store.dispatch("a/getData",100)

export default {
    created() {
      // 1直接使用.$store访问某块里面的action,dispatch函数的参数是"命名空间/action名字"
      this.$store.dispatch("a/getData",2)
    },
}

2先通过mapActions进行映射,...mapActions({b:"a/getData"})  this.b()

import {mapMutations} from "vuex"
export default {
    created() {
        this.b()
    },
    methods: {
 // mapActions()参数是一个对象 属性可以自定义属性,属性值模块中的action
      ...mapActions({b:'a/getData'}),   
    },
}

getters:

  1 $store.getters['a/done']

访问模块里面getter的时候 通过 $store.getters['a/getters']方式进行访问
    <p>{{$store.getters['a/done']}} 访问模块a里面的getters</p>

  2 先通过mapGetters进行映射,...mapGetters({b:"a/umcomplete",c:"a/done"})

import {mapGetters} from "vuex"
export default {
  computed:{
    ...mapGetters({b:"a/umcomplete",c:"a/done"})
  }
}

6.持久化存储

// 创建持久化存储对象
var vueLocal = new Vueinstance({
  // 存储方式,默认的是localStorage存储,可以修改成window.sessionStorage
  // storage:window.localStorage
  storage:window.sessionStorage
})

记得在组件中书写使用插件,使用持久化存储插件

  // 使用插件,使用持久化存储插件
  plugins:[vueLocal.plugin]

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值