状态管理组件--vuex

一、概念
vuex:状态(共享变量–>其他组件的功能)管理组件

state:放数据
views:显示数据,是.vue组件
action:更改数据

二、开发状态管理功能:
0 --> + -->1
1.安装vuex依赖

npm i --save vuex

写state:对象是常量,值是变量,指向地址不能变,指向空间的值是可变的。
在这里插入图片描述
在这里插入图片描述
根据基础知识,程序在启动时,会自动触发src/main.js,
因此,思路:可以将store.js暴露的多个对象封装到main.js中,
src/main.js–>store–>App.vue
程序的启动顺序:先main.js(store)–>App.vue,因此在使用App.vue时已经加载过了store,App.vue可以直接使用store,使用方式:$store

2.执行过程:store.js—>main.js–>组件(编写代码顺序)
在这里插入图片描述
在这里插入图片描述
2.1 store/index.js

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

Vue.use(Vuex)
//共享变量
const state={
  count:0
}
//直接操作共享变量的对象
const mutations={
  mulincrease(state){
    //自增1
    state.count++;
  }
}
//操作mulations的对象
const actions={
  //自增传入对象,然后调用
  actincrease({commit}){//传多个对象用{}
    commit('mulincrease');
  }
}
//将store.js中的对象暴露外界,用于其他组件的共享
export default new Vuex.Store({
  state,
  mutations,
  actions
})

2.2 main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store,//注入store对象,其中包含了state,mutations,actions
  render: function (h) { return h(App) }
}).$mount('#app')

2.3 App.vue

<template>
  <div id="app">
    {{$store.state.count}}
    <button @click="countinc">+</button>
  </div>
</template>

<script>
export default {
  methods:{
    countinc(){
      //store是一个全局对象,在方法内要用this来拿
      this.$store.dispatch('actincrease')
    }
  }
  
}
</script>

<style lang="scss">

</style>

2.4 结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值