vue之vuex的简单实用

最新在学习vue,简单的记录一下
先了解vuex有啥用?
vuex就是管理各组件的共有数据共享数据,向我们以前学习的data是组件的私有数据,需要通过props或者消息订阅离开完成各组件之间的传参,如果组件很多那么程序会写的很复杂,不好维护,2️⃣vuex则很好地解决了这个问题
安装vuex

>npm install --save vuex

创建store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
//状态对象
const state={
  counter:0
}
//包含多个更新state函数的对象
const mutations={
  ADD(state){
    state.counter++
  },JJ(state){
    state.counter--
  }
}
//包含多个事件回调函数的对象,actions调用mutations
const actions={
  add({commit}){
    commit('ADD');
  },
  jj({commit}){
    commit('JJ');
  },
  //待条件的action
  jjadd({commit,state}){
    if(state.counter%2===1)
    commit('ADD');
  },
  autoadd({commit}){
    setTimeout(()=>{
      commit('ADD');
    },1000)
  }
}
//包含多个更新state函数的对象
const getters={
  desc(state){//不需要亲自调用,只需要读取属性值
    return state.counter%2===0?'偶数':'奇数';
  }
}
export default new Vuex.Store({
  state,//状态对象
  mutations,//包含多个更新state函数的对象
  actions,//包含多个事件回调函数的对象
  getters//包含多个getter计算属性函数的对象
})

mian.js引入store.js

//入口js,创建vue实例
import Vue from 'vue'

import App from './App.vue'

import store from './store'


new Vue({
  el:'#app',
  components:{
    App,

  },
  template:'<App/>',
  store,//所有的组件对象都多了一个$store属性
})

app.vue

<template>
<div>
  <p>clicked  {{$store.state.counter}},counter is {{desc}}</p>
  <p>
    <button @click="add">+</button>
    <button @click="jj">-</button>
    <button @click="jjadd">奇数+1</button>
    <button @click="autoadd">过一秒自动+1</button>
  </p>
</div>

</template>

<script>

export default {

  name:'App',
  data(){
    return {

    }
  },
  computed:{
    desc(){
      return  this.$store.getters.desc;
    }
  },
  methods:{
    add(){

      this.$store.dispatch('add');//触发store中的actions调用
    },
    jj(){

      this.$store.dispatch('jj');//触发store中的actions调用
    },
    jjadd(){
      this.$store.dispatch('jjadd');//触发store中的actions调用
    },
    autoadd(){
      this.$store.dispatch('autoadd');//触发store中的actions调用
    }
  }

}
</script>
<style>


</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值