vuex 全局状态共享

``Vuex概述

  Vuex的核心概念

Vuex中的主要核心概念如下:

​     State:

​		State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储

```javascript
export default new Vuex.Store({
  state: {
      count:0
  }
})
```

​	组件中访问State中数据的第一种方式:

```javascript
this.$store.state.全局数据名称
```

​	组件中访问State中数据的第二种方式:

```javascript
//1.从vuex中按需导入mapState函数
import {mapState} from 'vuex'
```

通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的coumputed计算属性:

```javascript
//2.将全局数据,映射为当前组件的计算属性
computed:{
    ...mapState(['count'])
}
```

​	

​	Mutation:

​		Mutation用于变更Store中的数据

​			1.只能通过mutation变更Store数数据,不可以直接操作Store中的数据

​			2.通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。

```javascript
//在store中定义mutations
export default new Vuex.Store({
  state: {
    count:0
  },
  mutations: {
      add(state){
          state.count++;
      }
  }
})
```

```javascript
//在组件中触发store中的mutation中的函数
methods:{
	handle(){
		//触发mutation的第一种方式
		this.$store.commit('add');
	}
}
```

​	可以在触发mutation时传递参数:

```javascript
//在store中定义mutations
export default new Vuex.Store({
  state: {
    count:0
  },
  mutations: {
      addN(state,step){
          state.count+=step;
      }
  }
})
```

```javascript
//在组件中触发store中的mutation中的函数
methods:{
	handle(){
		//触发mutation的第一种方式
		this.$store.commit('addN',3);
	}
}
```

​	this.$store.commit()时触发mutation的第一种方式,触发mutation的第二种方式:

```javascript
//1.从vuex中按需引入mapMutations函数,映射为当前组件的methods函数
import {mapMutations} from 'vuex'
```

​	通过刚才引入的mapMutations函数,将需要mutations函数,转换为当前的methods方法:

```
//2.将指定的mutations函数,映射为当前组件的methods函数
methods:{
	...mapMutations(['add','addN'])
}
```

​	Action:

​		Action用于处理异步任务

​			如果通过异步变更数据,必须通过Action,而不能使用mutation,但是在Action中还是要通过Mutation的方式间接变更数据。

```javascript
export default new Vuex.Store({
  state: {
    count:0
  },
  mutations: {
    add(state){
        state.count++;
    }
  },
  actions: {
  	addAsync(store){
  		setTimeout(()=>{
  			context.commit('add');
  		},1000)
  	}
  },
})
```

​	在组件中触发Actions中的函数,第一种方式:

```javascript
methods:{
	handle3(){
        //这里的dispatch函数专门用来触发action
		this.$store.dispatch('addAsync');
	}
}
```

触发Actions的第二种方式:

```javascript
//1.从vuex中按需导入mapActions函数
import mapActions from 'vuex'
```

通过刚才导入的mapActions函数,将需要的actions函数,映射到当前组件的methodsf方法:

```
//2.将执行的Actions函数,映射为当前组件的methods方法:
methods:{
	...mapActions(['addAsync'])
}
```

Getter:

​	Getter用于对$sotre中的数据进行加工处理形成的数据。

​		1.Getter可以对store中已有的数据加工处理之后形成新的数据,类似于Vue的计算属性

​		2.Store中数据发生变化,Getter中的数据也会跟着变化

```javascript
export default new Vuex.Store({
	state:{
		count:0
	},
	Getter:{
		showNum(state)=>{
			return '当前最新的数量是【'+state.count+'】'
		}
	}
})
```

​	使用getters的第一种方式:

```javascript
this.$store.getters.名称
```

​	使用getters的第二种方式:

```javascript
import {mapGetters} from 'vuex'
computed:{
	...mapGetters(['showNum']);
}
```

```html

```

基于Vuex的案例

html 

<template>
  <div>
    <!-- Vuex 全局状态管理 -->
    <!-- 5个核心属性 -->
    <div>count:{{ count }}</div>
    <button @click="changeCount">count+100</button>
    <!-- 计算属性: 是函数 但 用的使用不要()触发 -->
    <div>翻倍:{{ $store.getters.count_fb }}</div>
    <div>翻倍:{{ count_fb }}</div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapGetters } from "vuex";
export default {
  computed: {
    ...mapState(["count"]),
    ...mapGetters(["count_fb"]),
  },
  computed: {
    count() {
      return this.$store.state.count;
    },
  },
  methods: {
    ...mapMutations(["updataCount"]),
    changeCount() {
      //修改state中的值
      //方法1:不推荐好用
      // this.$store.state.count+=100

      //方法2 mutations
      //触发方式:$store.commit(方法名)
      // this.$store.commit("updataCount");
      this.updataCount();
      console.dir(this);

      console.log("log:", this);
    },
  },
};
</script>

<style lang="scss" scoped>
</style>

store index.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
//引入外部模块
import user from './user'
Vue.use(Vuex)

export default new Vuex.Store({
  // state: 集中存储所有组件共享的状态
  state: {
    count: 100,
    news: null,
    meitu: null,
  },
  //流程:修改state中值
  mutations: {//负责修改stare中的值
    // 固定参数state   参数2 需要使用时传递具体的新闻内容
    updataCount(state) {
      state.count += 100
    },
    updateNews(state, news) {
      state.news = news
    },
    updateMeitu(state, meitu) {
      state.meitu = meitu
    }
  },
  //计算属性:利用state中已有属性 计算返回新的值
  getters: {
    //例如:count 翻倍
    count_fb(state) { //参数1:固定的state
      return state.count * 2
    }
  },
  //数据全局共享
  actions: {//所有actions中的方法,参数是固定的 store
    // 参数2:自定义传参,参数名随意
    getNews(store, page = 1) {
      console.dir(store);
      const url = 'https://api.apiopen.top/getWangYiNews?page=' + page
      // 在.vue文件中,this.axios 可以,因为this是vue对象
      //当前在.js文件中 需要手动引入axios模块
      axios.get(url).then(res => {
        console.dir(res);
        //把请求的数据 利用mutation中的 updateNews 方法进行更新
        store.commit('updateNews', res.data)
      })
    },

    getMeiTu(store) {
      const url = 'https://api.apiopen.top/getImages?page'
      axios.get(url).then(res => {
        console.dir(res);
        store.commit('updateMeitu', res.data)
      })
    }
  },
  modules: {
    // 导入外部的子模块
    user,
  }
})

actions   html

import { mapActions, mapState } from "vuex";
export default {
  computed: {
    ...mapState(["index", "hobby", "users", "kw"]),
  },
  data() {
    return {
      page: 0, 
    };
  },
methods: {
      ...mapActions(["getIndexUrl"]),
     }

第一种种方式通过映射传
mounted() {
    this.getIndexUrl(this.page);
    }

第二种方式通过映射传
methods:{
	handle3(){
        //这里的dispatch函数专门用来触发action
		this.$store.dispatch('addAsync',this.page);
	}
}
```

sorte  index.js

 
state: {
      
        index: [],
  }

mutations: { 
             getIndex(state, index) {
                  state.index = index
                }
          },

actions: {
        getIndexUrl(store, page) {
            axios.get(`v1/users/search?page=${page}`).then((res) => {
                console.log('首页表数据', res);
                store.commit('getIndex', res.data.data)

            });

        },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值