devx demo
启一个项目
vue init webpack-simple vuexdemo
cnpm intall
cnpm intall vuex -D (-D --save--dev)
cnpm install axios --save
npm run dev
vuex 中的两个方法
mapActions 管理事件
mapGetters 获取数据

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>vuexdemo</title>
</head>
<body>
<div id="app"></div>
<script src="/dist/build.js"></script>
</body>
</html>
App.vue 利用mapState 读取store.js中的state, 如下
<template>
<div id="app">
<input type="button" value="add" @click='increment'>
<p>现在的数字为{{$store.state.count}} </p>
<p>经过mapGetters 接受过来的值{{count}}</p>
</div>
</template>
<script>
import {mapActions, mapGetters,mapState} from 'vuex' //固定名称不可更更改
console.log(mapState)
export default {
updated:function(){
console.log(this.fn,this.count,this.orderList)
},
computed://经测试只能有一个的引入值,要不mapState,要不mapGetters,还需再测试
mapState([
'fn','orderList','count'
])
,
methods:mapActions([
'increment'
])
}
</script>
此处用到了mapState来接受 store.js中的state对象的值,也可以如下利用mapGetters得到store.js的getters对象的值,当然getters对象中要设置函数返回count的值
App.uve 利用mapGetters得到count,如下:
<template>
<div id="app">
<input type="button" value="add" @click='increment'>
<p>现在的数字为{{$store.state.count}} </p>
<p>经过mapGetters 接受过来的值{{count}}</p>
</div>
</template>
<script>
import {mapActions, mapGetters} from 'vuex'
export default {
computed:
mapGetters([
'count'
]),
methods:mapActions([
'increment'
])
}
</script>
store.js 其中
actions(要执行的动作,接受App.vue中mapAction发来的函数),
mutations(执行上面commit过来的函数,改变数据的变化),
state,(一系列的变量数据,对应App.vue中的mapState)
getters(返回数据用,对应App.vue中的mapGetters)
代码如下:
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) var state={ count:10, fn:'hell', orderList:{name:'liliy'} } const mutations={ increment(state){//处理(状态)数据的变化 state.count++ } } const getters={ count(state){ return state.count } } const actions={ increment:({//App.vue里的mapAction里定义的函数 commit //要干什么,执行时传入函数名进来,异步请求,判断,流程控制,名字不变 })=>{ commit('increment')//此处提交的increment可以变名称,但要保证和mutation里的一样 }//这里提完,去mutations里执行 /*等价于 increment:function({commit}){//{commit}==obj.commit commit('increment') }*/ } export default new Vuex.Store({ actions, mutations, state, getters })


浙公网安备 33010602011771号