vuex- 基础操作流程(数据不分块)

1.安装vuex

$ yarn add vuex 或者$npm i vuex -S

2.在src目录下创建store目录:

import Vuex from 'vuex'

import Vue from 'vue'

Vue.use( Vuex )

// 1. 定义store 模块

// const store = new Vuex.Store( options )

const store = new Vuex.Store({

state:{

count: 0

},

actions:

/*

1. actions是一个对象

2. acitons里面放的都是方法

3. 方法的作用是创建动作,发送动作

increment ( store对象,组件发来的实际参数1,参数2 ) {}

*/

increment ( { commit }, val ) {

console.log('increment执行了')

console.log('val', val )

// 动作创建

const action = {

type: INCREMENT,

val

}

// 发送动作

commit( action )

}

},

mutations:{

/*

* 也是一个对象

* 里面存放的也是方法

* 方法名称是actions发送来的动作的类型

* 接收两个参数

* state就是数据 , action就是actions发来的动作

* mutations作用是用来修改数据的

* payload表示从组件传递过来的参数 负载

*/

[ INCREMENT ] ( state,action ) {

console.log('mutations执行了')

console.log( 'state',state)

console.log( 'action',action )

//修改数据

state.count ++

}

},

getters: {}, //getters表示帮助 视图【 组件 】 获得store中的 state

modules // 用来实现数据分块的

/*

数据分块:

一个项目中是有多个功能或是页面的,比如有

home

分类

列表

详情

用户

普通用户

会员

超级会员

底部栏

头部栏

图表数据

一个state管理所有的这些数据,就会变的杂乱,和不好维护,所以我们希望将数据分块,单一管理,一个数据一个模块

*/

})

// 2. 导出store模块

export default store

3.main.js中注入store

import store from './store'

new Vue({

router, // 在项目中注入路由,让所有的子组件都用于路由属性 $route $router

store, // 在项目中注入store,让所有的子组件拥有一个属性 $store , 用于和vuex进行通信

render: h => h(App),

}).$mount('#app')

4.在组件内使用:

<template>

<div> vuex - 基础 <hr/> <button @click = "add"> + </button>

<p> {{ $store.state.count }} </p>

</div>

</template>

<script>

export default {

methods: {

add () {

// 执行actions中的increment方法

// this.$store.dispatch( actions中方法的名称 )

this.$store.dispatch('increment',100)

}

},

created () {

console.log( this.$store )

}

}

</script>

 

转载于:https://www.cnblogs.com/zjp-com/p/11455980.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值