1.创建一个js文件 ,可以全局注册也可以在单个组件引用,我这里创建vuex文件夹,创建store.js,我没有全局注册
单个组件引用 import store from '../store/index.js'
store.state.playing=true;,只能这样简单粗暴的修改 或展示 store.commit('isrotate');
全局引用
import store from './store'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
this.$store.commit('isrotate');
const mutations={
isrotate(state){
state.playing=true;
},
norotate(state){
state.playing=false;
}
}
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
//数据源
const state={
count:1
};
//getters属性 暂时没用到
const getters ={
fn:function(state){
return state.count+=100;
}
};
//固定写法 修改状态同步
const mutations ={
add(state){
console.log("1")
state.count++;
},
reduce(state){
state.count--;
}
};
//修改状态 异步 调用了mutations里的方法
const actions = {
addA(context){
console.log("2")
context.commit('add',10)
},
redA({commit}){
commit('reduce',10)
},
};
//这里一定要记得导出
export default new Vuex.Store({
state,getters,mutations,actions,
})
然后在需要用到这个数据的组件里引入
import store from '../vuex/store';
//import { mapGetters } from 'vuex'
export default {
store, //这里一定要调用
data(){
return{
msg:23,
}
},
computed:{
//...mapGetters(["fn"]),
count1(){
return store.state.count;
// return this.$store.getters.count;
}
},
<h3>{{$store.state.count}}</h3> //1 先展示 接下来修改
<button @click="$store.commit({type: 'add'})">点击加1</button>
<button @click="$store.commit('reduce')">点击减一</button>
//这里是调用mutations 里的方法
<button @click="add2()">++++++++</button>
<button @click="red2()">----------</button>
methods{
adds(){
this.$store.dispatch('addA',2)
},
reds(){
this.$store.dispatch('redA')
},
}
//这里是 actions 里的方法
直接获取vuex里的数据
mounted() {
console.log(store.state.pie);
console.log(this.$store.state.pie);
// this.draw(this.$store.state.pie)
},
语法糖写法
import {mapState} from 'vuex';
computed: { ...mapState(['good']) },