vuex+elementUI&如何使用vuex?&如何安装vuex?

转载请标明出处:https://blog.csdn.net/men_ma/article/details/106847165.
本文出自 不怕报错 就怕不报错的小猿猿 的博客

前言

本次目标

1、了解vuex中的各个js文件的用途
2、利用vuex存值
3、利用vuex取值
4、Vuex的异步加载问题

学习vuex的目的是为什么

vuex是为了解决传值的问题,前面的博客中讲了两种传值的方式,父传子和子传父,这两种的的传值方式都很麻烦,随后就出现了总线传值,也有缺陷,所以现在我们用vuex来解决传值的问题(子孙很多代)
在这里插入图片描述

1.vue中各个组件之间传值

1. vue中各个组件之间传值
   1.父子组件
   父组件-->子组件,通过子组件的自定义属性:props
   子组件-->父组件,通过自定义事件:this.$emit('事件名',参数1,参数2,...);
 
   2.非父子组件或父子组件
   通过数据总数Bus,this.$root.$emit('事件名',参数1,参数2,...)
 
   3.非父子组件或父子组件
   更好的方式是在vue中使用vuex
 
   方法1: 用组件之间通讯。这样写很麻烦,并且写着写着,估计自己都不知道这是啥了,很容易写晕。
   方法2: 我们定义全局变量。模块a的数据赋值给全局变量x。然后模块b获取x。这样我们就很容易获取到数据
 

2.vuex中的各个js文件的用途

vuex是专为vue.js应用程序开发的状态管理模式。
vuex用于集中管理整个vue项目中的所有变量,就好比一个数据库

如下图(图解Vuex各组件):

在这里插入图片描述
官方图解Vuex:
在这里插入图片描述

注1:
状态管理有5个核心,分别是state、getter、mutation、action以及module。分别简单的介绍一下它们:

1、state:单一状态树

        state为单一状态树,在state中需要定义我们所需要管理的数组、对象、字符串等等,只有在这里定义了,在vue.js的组件中才能获取你定义的这个对象的状态。

2、getter:状态获取

        getter有点类似vue.js的计算属性,当我们需要从store的state中派生出一些状态,那么我们就需要使用getter,getter会接收state作为第一个参数,而且getter的返回值会根据它的依赖被缓存起来,只有getter中的依赖值(state中的某个需要派生状态的值)发生改变的时候才会被重新计算。

3、mutation:触发同步事件

        更改store中state状态的唯一方法就是提交mutation,就很类似事件。每个mutation都有一个字符串类型的事件类型和一个回调函数,我们需要改变state的值就要在回调函数中改变。我们要执行这个回调函数,那么我们需要执行一个相应的调用方法:store.commit。

4、action:提交mutation,可以包含异步操作

        action可以提交mutation,在action中可以执行store.commit,而且action中可以有任何的异步操作。在页面中如果我们要嗲用这个action,则需要执行store.dispatch

5、module:将vuex进行分模块

        module其实只是解决了当state中很复杂臃肿的时候,module可以将store分割成模块,每个模块中拥有自己的state、mutation、action和getter。

3.vuex使用步骤

3.1 安装

 npm install vuex -S

在这里插入图片描述

3.2 创建store模块,分别维护state/actions/mutations/getters

各模块的作用前面已介绍

 store
        index.js  默认模块
        state.js
        actions.js
        mutations.js
        getters.js
  

在这里插入图片描述

3.3 在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块

  
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
const store = new Vuex.Store({
 	state,
 	getters,
 	actions,
 	mutations
 })

 export default store

在这里插入图片描述

3.4 在main.js中导入并使用store实例

 import store from './store'

      new Vue({
el: '#app',
router,
store, //在main.js中导入store实例
components: {
App
},
template: '<App/>',
data: {
//自定义的事件总线对象,用于父子组件的通信
Bus: new Vue()
}
      })

在这里插入图片描述

3.5 之后按要求编码,即可使用vuex的相关功能

3.6 vuex的核心概念:store、state、getters、mutations、actions

 4.0 store
      每一个Vuex应用的核心就是store(仓库),store基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
      const store = new Vuex.Store({
       state,    // 共同维护的一个状态,state里面可以是很多个全局状态
       getters,  // 获取数据并渲染
       actions,  // 数据的异步操作
       mutations  // 处理数据的唯一途径,state的改变或赋值只能在这里
      })
 

4.Vuex取值

4.1 第一张取值方式:this.$store.state.resturantName(不推荐)

  1 state(保存数据的容器)
      状态,即要全局读写的数据
      const state = {
        resturantName:'飞歌餐馆'
      };
 
      this.$store.state.resturantName;//不建议
 
2 getters(getXxx)
     获取数据并渲染,
     const getters = {
       resturantName: (state) => {
         return state.resturantName;
       }
     };
 
     注1:getters将state中定义的值暴露在this.$store.getters对象中,我们可以通过如下代码访问
          this.$store.getters.resturantName
 
     注2:state状态存储是响应式的,从store实例中读取状态最简单的方法就是在计算属性中返回某个状态,如下:
          computed: {
            resturantName: function() {
              return this.$store.getters.resturantName;
            }
          }
      

在这里插入图片描述
第一张页面:
在这里插入图片描述
第二张页面:

在这里插入图片描述

第一张页面取值的效果(说明vuex能够正常使用):
在这里插入图片描述
第二张页面取值的效果(说明vuex能够正常使用):
在这里插入图片描述

4.2 第二种取值方式:利用getters箭头函数获取值(推荐使用)

在这里插入图片描述
在这里插入图片描述
第二张页面取值的效果(getters取值):

在这里插入图片描述

5 Vuex存值

处理数据的唯一途径,state的改变或赋值只能在这里
 
      export default {
        // type(事件类型): 其值为setResturantName
        // payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器
setResturantName: (state, payload) => {
          state.resturantName = payload.resturantName;
}
      }
 
      注1:mutations中方法的调用方式
           不能直接调用this.$store.mutations.setResturantName('KFC'),必须使用如下方式调用:
           this.$store.commit(type,payload);
 
           // 1、把载荷和type分开提交
           store.commit('setResturantName',{
             resturantName:'KFC'
           })
 
           // 2、载荷和type写到一起
          store.commit({
            type: 'setResturantName',
            resturantName: 'KFC'
          })
           
      注2:一定要记住,Mutation 必须是同步函数。为什么呢?异步方法,我们不知道什么时候状态会发生改变,所以也就无法追踪了
           如果我们需要异步操作,Mutations就不能满足我们需求了,这时候我们就需要Actions了
           mutations: {
            someMutation (state) {
              api.callAsyncMethod(() => {
                state.count++
              })
            }
           }

5.1 mutations同步传值(也就是set值)

mutations.js

export default {//同步操作
	// payload:载荷,其实就是一个保存要传递参数的容器 说白了就是json对象
	setResturantName:(state,payload)=>{
		state.resturantName=payload.resturantName
	}
}

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

6.Vuex异步加载(action.js)

export default {
	setResturantNameByAsync: (context, payload) => {
		console.log('xxxx');
		setTimeout(() => {
			console.log('yyyy');
			console.log(payload)
			// state.resturantName = payload.resturantName;
			context.commit('setResturantName', payload); //Action提交的是mutation
		}, 3000)
		console.log('zzzz');
	},
	doAjax: (context, payload) => {
		let _this = payload._this
		let url = _this.axios.urls.SYSTEM_USER_DOLOGIN;
		_this.axios.post(url, {}).then((response)=> {
			console.log(response);
			
			
		}).catch(function(error) {
			console.log(error);
		});
	}
}

Action类似于 mutation,不同在于:
1.Action提交的是mutation,而不是直接变更状态
2.Action可以包含任意异步操作
3.Action的回调函数接收一个 context 上下文参数,注意,这个参数可不一般,它与 store 实例有着相同的方法和属性
但是他们并不是同一个实例,context 包含:
1. state、2. rootState、3. getters、4. mutations、5. actions 五个属性
所以在这里可以使用 context.commit 来提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

注1:actions中方法的调用方式语法如下:
this. s t o r e . d i s p a t c h ( t y p e , p a y l o a d ) ; 例 如 : t h i s . store.dispatch(type,payload); 例如:this. store.dispatch(type,payload);this.store.dispatch(‘setResturantNameByAsync’,{resturantName: ‘啃德鸡2’});

注2:action中提交mutation
context.commit(‘setResturantName’,{resturantName: ‘啃德鸡2’});

注3:VUEX 的 actions 中无法获取到 this 对象
如果要在actions 或者 mutations 中使用this对象。可以在调用的时候把this对象传过去
{resturantName: ‘啃德鸡2’,_this:this}//this就是在调用时的vue实例

Vuex中actions的使用场景
场景1:部门管理中添加或删除了新的部门,员工新增/编辑页面的部门列表需要进行变化
场景2:vuex之使用actions和axios异步初始购物车数据

6.1 action.js:异步加载

在这里插入图片描述

总代码

VuexPage1.vue:

<template>
	<div>
		<ul>
			<li>这是第一张页面:{{msg}}</li>
			<li>
				<input v-model="newName" />
				<button @click="buy">盘他</button>
				<button @click="badBuy">有阴谋</button>
				<button @click="doAjax">调用ajax</button>
			</li>
		</ul>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				newName:''
			};
		},
		computed:{
			msg(){
				//this.$store.state.resturantName取值不推荐 
				  // 因为vuex遵循了解耦的规则 ,各模块各司其职
				console.log(this.$store);
				
				return this.$store.state.resturantName;
			}
		},
		methods:{
			buy(){//同步传值
				console.log(this.newName);
				// commit:同步传值调用
				this.$store.commit('setResturantName',{
					resturantName:this.newName
				})
			},
			badBuy(){//异步传值
				// dispatch:异步传值调用
				this.$store.dispatch('setResturantNameAsync',{
					resturantName:this.newName
				})
			} , 
			 doAjax(){
				this.$store.dispatch('doAjax',{
					_this:this
				})
			}
		}
	}
</script>

<style>

</style>

VuexPage2.vue:

<template>
	<div>
		<ul>
			<li>这是第二张页面:{{msg}}</li>
		</ul>
	</div>
</template>

<script>
	export default {
		data() {
			return {

			};
		},
		computed:{
			msg(){
				//推荐使用
				return this.$store.getters.getResturantName;
			}
		}
	}
</script>

<style>

</style>

配置路由:

import VuexPage1 from '@/views/sys/VuexPage1'
import VuexPage2 from '@/views/sys/VuexPage2'



	{
					path: '/sys/VuexPage1',
					name: 'VuexPage1',
					component: VuexPage1
				},
				{
					path: '/sys/VuexPage2',
					name: 'VuexPage2',
					component: VuexPage2
				}

在这里插入图片描述
在这里插入图片描述

效果

效果1:点击“盘它”
在这里插入图片描述

效果2:点击有阴谋

在这里插入图片描述
点击有阴谋,第二张页面的msg也会随之改动
在这里插入图片描述

效果3:vuex中调用ajax
在这里插入图片描述

总结

vuex 解决了:spa项目原有的总线传参,变量定义过于分散,不方便项目维护,这一问题

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值