store页面中的配置信息
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
//存贮store中的数据
state: {
counter: 0
},
//相当于store中的计算属性
getters: {
plus2(state) {
return state.counter%2 == 0?'偶数':'奇数'
}
},
//处理store中的数据
mutations: {
add(state) {
state.counter++
}
},
//处理mutation中的方法
actions: {
// add(context) {
// context.commit('add');
// }
add({commit}){
commit('add');
}
},
modules: {
}
})
主页面
<template>
<div id="app">
<img src="./assets/logo.png">
<!-- <HelloWorld msg="Welcome to Your Vue.js App"/> -->
<!-- <communication></communication> -->
<!-- <slot-example></slot-example> -->
<!-- <form-example></form-example> -->
{{$store.state.counter}}
<button @click="$store.commit('add')">+</button>
<button @click="add">+</button>
{{plus2}}
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import communication from '@/components/communication';
import SlotExample from '@/components/slots'
import FormExample from '@/components/form'
//引入辅助函数
import { mapGetters,mapActions } from 'vuex';
export default {
name: 'app',
components: {
HelloWorld,
communication,
SlotExample,
FormExample
},
methods:{
// add(){
// // 调用actions的方法,dispathch是vuex中的实现方式
// this.$store.dispatch('add');
// }
...mapActions['add'],
//本页面的其他方法
},
computed:{
...mapGetters(['plus2']),
// 可以写本页面的计算属性
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
本次学习到的几个主要概念
state:存放全局状态数据
mutation:修改数据的唯一入口
gettters:相当于store中的计算属性
关于actions,可以用来处理异步的commit发送
actions : {
add(context,payload){
$.get("api.txt",function(data){
context.commit('add',Number(data));
});
}
},
.vue文件
<style scopoed>
</style>
<template>
<div>
我是子组件
<h1>
<button v-on:click="minusnandler">减少</button>
{{count}}
<button v-on:click="addhandler">增加</button>
</h1>
<h1>
{{nansheng}}
</h1>
</div>
</template>
<script>
export default {
data(){
return {
m : 6,
n : 0
}
},
computed : {
count(){
return this.$store.state.count;
},
nansheng (){
return this.$store.getters.nansheng
}
},
methods : {
addhandler(){
this.$store.dispatch("add"); //添加的数字写在文本文件中了,是异步读取的,所以不能直接commit
},
minusnandler(){
this.$store.commit("minus");
}
}
}
</script>