Vue.js之vuex入门

5 篇文章 0 订阅
1 篇文章 0 订阅

放图,这个图最能说明vuex和Vue之间的关系。
在这里插入图片描述

一、原理

虚线中的Vuex是用来处理vue的组件,vue compontents(组件)通过dispatch(理解为转发事件)交给action,通过接入后端api完成一些业务,在action中进行异步操作,再将结果以commit(提交事件)方式发给mutations。mutations中最终实现vue compontent的method。state用来存数据,交给组件在页面中显示。

devtools是vue为了适应浏览器的一个插件,在这个插件中可以看到vue响应的过程,包括每个对象,属性和value。
在这里插入图片描述
在这里插入图片描述

二、vuex组成

1、state
2、getter
3、mutations
4、actions
5、modules

1. state

相当于数据仓库,vuex中的数据放在store实例中,store对象包括 s以上5个部分。
store称为单一状态树:所有状态信息保存在一个store中,便于管理。

const store= new Vuex.Store({
  state:{
    //counter 数据变量
//保存数据,在其他地方引用$store.state.counter
  },}

2. getter
用来获取数据,类似computed计算属性。

getters:{
    // adddd(){
    // }
//类似计算属性computed,使用时$store.getter.adddd}

//filter过滤,s代表student数组中的一个,结果返回学生信息。
this.$store.state.student.filter(s =>{ 
        Return s.age>20})
等价于:
this.$store.student.filter(s=> s.age>=20) 
//前一个>= 是过渡函数,filter格式,第二个>=是判断条件

more20(state){

    },
    more20Length(state,getter){
      //调用getter中已有的函数getter.more20.length
    }
  },

3. mutations
在mutations中,vue组件的method,commit给mutation,mutation来处理。
用来修改数据,包括两部分:事件类型type+回调函数;
回调函数的参数被称为mutation的负载payload。

两种提交风格:
	this.$store.commit(“appmethodTomutation”,count)
//此处事件类型appmethodTomutation,payload:count

//可以直接由vue.component-->mutations,执行同步操作
//如果有异步操作,则需要vue.component-->actions-->mutations
	this.$store.commit({
type:” appmethodTomutation”,   count   })
  • 响应式原理:界面刷新,state中的属性值跟着刷新。如果初始没有该属性,则不跟随响应。
  • 添加属性:并跟随响应的方法push,pop,Vue.set(state.info,‘address’,’shandong’)
  • 删除属性:Vue.delete(state.info,’age’)
  • Miutation常量:将方法定义为常量,commit时写常量。
//常量:
this.$store.commit(INCERES)
//在mutation中 使用
[INCRESE]{方法  }   
//还需要在mutation.js中单独定义
 export const INCRESE=‘increse’

4.actions
vue的method dispatch给action,actions 中commit 给 mutations,最终在mutation中解决。
action执行异步操作:
(如setTimeout(()=>{ state.info.name=’xlkhj’ }, 1000),在mutation中都是同步操作。
Context上下文,相当于store

在这里插入图片描述
在这里插入图片描述
5. modules
store内容过多时可使用,将store的功能模块化,每个模块中又可以有state等。从module中的action取store中的值context.rootGetters。

三、在vue中使用vuex

Vue.use(Vuex)
//1、安装插件
//2、创建store对象
const store= new Vuex.Store

// 3、导出store对象:
export default store

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值