1.安装vuexvue
$ yarn add vuex 或者$npm i vuex -Svuex
2.在src目录下建立store目录:npm
import Vuex from 'vuex'app
import Vue from 'vue'this
Vue.use( Vuex )spa
// 1. 定义store 模块router
// const store = new Vuex.Store( options )对象
const store = new Vuex.Store({ip
state:{ci
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>