vuex的学习

1 篇文章 0 订阅

vuex

专门在vue中实现集中式状态(数据)管理的一个插件,对vue应用中多个组件的共享状态进行集中式的管理,也是一种组件间的通信方式,且适用于任意组件间通信

状态机管理 vue全家桶之一

数据的集中式管理

什么时候用:当多个组件共享数据的时候

安装
$ npm install vuex --save
使用

创建store文件夹在src下,再创建一个index.js store 是一个仓库

1.引用vue ,vuex

2.使用vuex Vue.use(vuex)

3.准备actions,mutations,state

4.创建vuex实例

// 引入vuex
import Vuex from 'vuex'
// 引入vue
import Vue from 'vue'
Vue.use(Vuex)

// 准备actions
const actions={

}
// 准备mutations
const mutations={

}
// 准备state
const state={

}
const store=new Vuex.Store({
    actions,
    mutations,
    state
})
export default store

在main.js中引入store配置

import store from './store/index'
基本使用-案例

实现加减法计算的实例:

1.创建home.vue组件在component文件夹下面

<template>
  <div class="home">
    <h2>我是Home组件</h2>
   <h3>计算结果:{{result }}</h3>
    <h3>学校:{{ school }}</h3>
    <h3>姓名:{{myname }}</h3>
	<button @click="addHandler(1)">+</button>|
    <button @click="jianHandler(1)">-</button>|
    <button @click="waitHandler(1)">等会在加</button>
  </div>
</template>

<script>
// 引入辅助函数
import { mapMutations, mapState, mapGetters, mapActions } from "vuex";
export default {
  name: "Home",
  data() {
    return {};
  },
  // 计算属性
  computed: {
     result(){
        return this.$store.state.result
     },
     school(){
         return this.$store.state.school
     },
     myname(){
        return this.$store.state.myname
     }
  },
  methods: {
    addHandler(v) {  
       //从state开始准备数据
      this.$store.dispatch('jia',v)
    },
    jianHandler(v) {
     //直接跳过state,到mutation开始准备数据
      this.$store.commit('jian',v)
  
    },
    waitHandler(v) {
      // setTimeout一定要写箭头函数,this指向才对,普通函数的this会指向window
      setTimeout(()=>{
       this.$store.commit("wait", v);
      },2000)
      
    },
  },
  // 钩子函数
  created() {
  	console.log(this.$store,'@@@');    
  },
};
</script>
<style scoped>
</style>

2.给vuex实例对象添加数据方法

// 引入vuex
import Vuex from 'vuex'
// 引入vue
import Vue from 'vue'
Vue.use(Vuex)

// 准备actions
const actions = {
    jia(context, value) {
        // console.log('jia',context);
        // console.log(value);
        context.commit('JIA', value)
    },

}
// 准备mutations
const mutations = {
    JIA(state, value) {
        // console.log('mutations');
        // console.log(state,value);
        state.result += value
    },
    jian(state, value) {
        state.result -= value
    },
    wait(state, value) {
        setTimeout(() => {
            state.result += value
        }, 2000)
    }
}
// 准备state
const state = {
    result: 1,
    school: 'briup',
    myname: 'zhangsan'
}
const store = new Vuex.Store({
    actions,
    mutations,
    state
})
export default store

组件中读取vuex中的数据

​ $store.state.result

组件中修改vuex中的数据

s t o r e . d i s p a t c h ( ′ a c t i o n s 中 的 ⽅ 法 名 ′ , 数 据 ) 或 store.dispatch('actions中的⽅法名' ,数据)或 store.dispatch(actions)store.commit(‘mutations中的⽅法名’,数据)

备注:若没有⽹络请求或其他业务逻辑,组件中也可以越过actions,即不写 dispatch ,直接编写 commit

getter配置对象

概念:当state(仓库)中的数据需要经过加工后再使用,可以使用getter加工

用法:在store的index.js中追加getter配置

// 准备getters
const getters = {
    bigResult(state) {
        return state.result * 10
    }
}
const store = new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})

在组件中读出数据使用:$store.getters.bigResult()

//渲染数据
<h3>计算结果的10倍:{{bigResult}}</h3>


<script>
	computed: {
		bigResult(){
      		return this.$store.getters.bigResult
   		 }
	}
</script>
四个map方法的使用(辅助函数)
  • mapState
  • mapGetters

由于 state和getters是存储数据的,因此这两个辅助函数引用的时候一般写在计算属性computed里面

  • mapActions
  • mapMutations

由于actions和mutations是存储异步请求数据方法和存储修改数据方法的,因此这两个辅助函数引用的时候一般写在methods里面

辅助函数的写法有两种

  1. 对象方法
...mapActions({jia:'jia'})
...mapMutations({jian:"jian"})


...mapState({shool:'school',result:'result',myname:'myname'})
...mapGetters({bigResult:'bigResult'})
  1. 数组方法
...mapActions(['jia'])
...mapMutations(["jian"])


...mapState(['school','result','myname'])
...mapGetters(['bigResult'])
模块化

在相应的模块导出的时候,添加属性namespaced,并且设置为true

const homeAbout = {
    namespaced: true,
    actions: {
        jia(context, value) {
            // console.log('jia',context);
            // console.log(value);
            context.commit('JIA', value)
        },
    },
    mutations: {
        JIA(state, value) {
            // console.log('mutations');
            // console.log(state,value);
            state.result += value
        },
        jian(state, value) {
            state.result -= value
        },
        wait(state, value) {
            setTimeout(() => {
                state.result += value
            }, 2000)
        }
    },
    state: {
        result: 1,
        school: 'briup',
        myname: 'zhangsan'
    },
    getters: {
        bigResult(state) {
            return state.result * 10
        }
    }
}

const aboutAbout = {
    namespaced: true,
    actions: {

    },
    mutations: {
        update(state,value){
            state.about=value
        }
    },
    state: {
        result: 1,
   		school: 'briup',
    	myname: 'zhangsan',
    	about:'我是about页面'
    },
    getters: {

    }
}

const store = new Vuex.Store({
    //actions,
   // mutations,
   // state,
  //  getters
    modules:{
     homeAbout,
     aboutAbout
    }
})

export default store

调用具体模块的的方法

格式:…mapxxxx(‘模块名称’,[‘模块里面的数据/方法’])

...mapActions('homeAbout',['jia'])
...mapMutations('aboutAbout',["update"])

...mapState('aboutAbout',['school','result','myname'])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值