vue插件的一些使用:
时间旅行(查看过去每个 muation ) 状态的快照
撤销该时刻之后的
提交该mutation 时刻,随后的操作以该位置为时间基准
count:(计数器)
App.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png" />
<h1>{{count}}</h1>
<div>
<button @click="increment(1)">+</button>
</div>
<div>
<button @click="decrement(-1)">-</button>
</div>
<h1>奇偶:{{ isOdd}}</h1>
<h1>一半:{{half_count}}</h1>
<div><button @click="set">重置</button></div>
</div>
</template>
<script>
import { mapState, mapMutations, mapGetters ,mapActions} from "vuex";
export default {
name: "App",
components: {},
methods: {
// 导入映射中的store中的
// ...对象展开运算符
...mapMutations(["increment", "decrement"]),
...mapActions(['reset']),
set:function(){
// 不使用mapActions就可以调用
// this.$store.dispatch('reset',5000);
// 先mapActions才能调用
this.reset(999);
}
// inc: function() {
// // 没有使用 vuex 中标准流程,很多特性,优势,可以勉强工作
// // this.$store.state.count++;
// // 在计算属性中导入的状态是只读的,不可以改变,使用mutation(改变,)去改变
// // this.count++; 错误的
// // type:类型,payload:负载就是参数
// this.$store.commit('increment',1);
// },
// dec: function() {
// // 没有使用 vuex 中标准流程,很多特性,优势,可以勉强工作
// // this.$store.state.count--;
// // 在计算属性中导入的状态是只读的,不可以改变,使用mutation(改变,)去改变
// // this.count--; 错误的
// this.$store.commit('decrement',{x:1,y:2});
// }
},
// mapState的三种写法
// 1.可以起别名,重命名,键值对
// computed: mapState({
// n: "count"
// })
// 2. 映射过来的属性一样
// computed: mapState(['count']),
// 3.混合:可以导入store中的,还可以自定义局部的,推荐使用第三种,
// 在计算属性中导入状态的映射并定义局部(组件内)的计算属性
// ...对象
computed: {
...mapState(["count"]),
// ...mapGetters(["oddOrEven"]),
// 指定别名
...mapGetters({
isOdd: "oddOrEven"
}),
// 组件内部的
half_count() {
// 是否修改count?是读
return this.count / 2;
}
}
};
</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>
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
// 应用级的状态,不是局部状态
// 组件中访问store状态
// 1.$store.state.count
// 2.computed: {
// n:function(){
// return this.$store.state.count;
// }
// },
// 推荐使用
// 3. <h1>{{count}}</h1>
// <script>
// import { mapState } from "vuex";
// export default {
// name: "App",
// components: {},
// computed: {
// ...mapState([
// 'count'
// ]),
// // 组件内部的
// inner(){
// return '组件内部定义的计算属性';
// }
// }
// };
// </script>
// 4. getCount(state){
// return state.count;
// }
state: {
// 计数器的计数值
count: 0
},
// 使用mutation改变状态
mutations: {
increment(state){
state.count++;
},
decrement(state){
state.count--;
},
clear(state,n){
state.count=n;
},
http(){
console.log("net...");
}
},
actions: {
// 方案一
// reset(context,n){
// // action提交一个特定的mutation
// context.commit("clear",n);
// context.commit("http");
// }
// 方案二
reset({commit},n){
// action提交一个特定的mutation
commit("clear",n);
commit("http");
}
},
// 过滤作用,第一个参数为state
getters: {
oddOrEven(state){
// 基于状态执行计算的表达式
return state.count%2===0?'偶数':'奇数';
}
}
})