Vuex_demo

在这里插入图片描述

  • 1.在src目录中新建store文件,store文件夹中新建index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// new Vuex.Store 创建对象
export default new Vuex.Store({
	state:{
	...共享的数据
		count:0
	},
	 // 对state中的数据进行处理,不会修改
	getters:{
		...方法
		showNum(count){
		 return state.count
		}
	},
	// 更新state中的数据,只能执行同步操作
	mutations:{
		... 方法
		add(state){
			state.count++
		}
	}
	
	 // 用于处理异步任务
	  actions: {
        addAsync(context) {
            setTimeout(() => {
                // actions中,不能直接修改state中的数据
                // 必须通过context.commit触发mutation中的函数执行
                context.commit('add')
            }, 1000)
        },

vuex状态的所有改变都必须在store的mutation中进行修改

2.main.js

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

Vue.config.productionTip = false

new Vue({
  store,
  render: h => h(App)
}).$mount('#app')


// 使用el挂载
new Vue({
	el:'#app',
	render:h => h(App),
	store,
})

3.子组件add.vue

<template>
    <div>
        <!-- this.$store.state访问全局共享数据 -->
        <h3>当前最新的count:{{$store.state.count}}</h3>
        <h3>
            {{$store.getters.showNum}}
        </h3>
        <button @click="btnHandleAdd">+1</button>

    </div>
</template>

<script>
export default {
    data(){
        return{

        }
    },
     methods:{
      // 同步操作    commit触发mutations操作
        btnHandleAdd(){
            this.$store.commit('add')

        },
        
         // 异步触发  dispatch触发actions操作
        btnHandleAddAsync(){
            this.$store.dispatch('addAsync')
        },
 }
</script>
  • 获取变量名:this.$store.state.变量名

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值