VUEX学习笔记

10 篇文章 0 订阅

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'])
},

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值