npm install vuex --save
在package.json出现vuex,表示安装成功
初步使用,构建公用数据存储
新建vuex文件夹和store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
// 声明一个常量
const state={
count:1
}
//操作变量的方法
const mutations={
add(state){
state.count++;
},
reduce(state){
state.count--;
}
}
// 外面使用需要进行暴露
export default new Vuex.Store({
state,
mutations
})
<script>
// 导入外部js文件
import store from "@/vuex/store";
export default {
name: "Count",
data() {
return {
msg: "Hello Vuex"
};
},
store
};
script>
注意:导入js的方式和export default中要加上store
<div>
<h2>{{msg}}h2><hr/>
<h3>{{$store.state.count}}h3>
<p>
<button @click="$store.commit('add')">+button>
<button @click="$store.commit('reduce')">-button>
p>
div>
<h3>{{$store.state.count}}--{{count}}h3>
目的:让$store.state.count的值赋给count,使用count直接显示结果
<template>
<div>
<h2>{{msg}}h2><hr/>
<h3>{{$store.state.count}}--{{count}}h3>
<p>
<button @click="$store.commit('add')">+button>
<button @click="$store.commit('reduce')">-button>
p>
div>
template>
<script>
// 导入外部js文件
import store from "@/vuex/store";
//方式二 利用mapState这里注意mapState要加{},文档有坑(这一这里mapState和store.js中state保持一致)
import {mapState} from 'vuex';
export default {
name: "Count",
data() {
return {
msg: "Hello Vuex"
};
},
// 方式一: 重新计算
// computed:{
// count(){
// return this.$store.state.count;
// }
// },
// 方式二 利用mapState
// computed:mapState({
// count:state=>state.count
// }),
//方式三 数组形式(常用)
computed:mapState(['count']),
store
};
script>
//操作变量的方法
const mutations={
add(state,n){
// state.count++;
state.count+=n;
},
reduce(state){
state.count--;
}
}
调用
修改方法:
a、引入:
//方式二 利用mapState这里注意mapState要加{},文档有坑
import {mapState, mapMutations} from 'vuex';
这里要加mapMutations
b、重写
methods:mapMutations(['add','reduce']),
c、使用
<button @click="reduce">-button>
每次对state.count的操作都会经过这个过滤操作
store.js中操作
//getters计算过滤操作
const getters={
count:function(){
return state.count+=10;
}
}
// 外面使用需要进行暴露
export default new Vuex.Store({
state,
mutations,
getters
})
在模板中使用:
import { mapState, mapMutations, mapGetters}
computed: {
...mapState(['count']),
// count(){
// return this.$store.getters.count;
// }
...mapGetters(['count'])
},
在store.js中
// actions异步修改状态
const actions={
addAction(context){
context.commit('add',10);
setTimeout(()=>{
context.commit('reduce')
},3000);
},
reduceAction({commit}){
commit('reduce');
}
}
// 外面使用需要进行暴露
export default new Vuex.Store({
state,
mutations,
getters,
actions
})
在模板中
import { mapState, mapMutations, mapGetters, mapActions }
methods:{
...mapMutations(["add", "reduce"]),
...mapActions(["addAction", "reduceAction"])
},
在store.js中
//module模块组
const moduleA={
state,
mutations,
getters,
actions
}
// 外面使用需要进行暴露
export default new Vuex.Store({
modules:{a:moduleA}
})
在模块中使用
{{$store.state.a.count}}