Vue学习笔记 —— Vuex基础

这篇博客介绍了如何在Vue项目中安装和使用Vuex。首先在项目根目录下创建Vuex文件夹,然后初始化store并将其挂载到Vue实例上。在组件中可以直接访问Vuex状态。对于数据修改,通过Mutations来实现,包括增删操作,并展示了Mutation的单个参数和多个参数用法。此外,文章还提到了Actions用于处理异步操作,演示了如何调用Actions中的方法以每两秒执行一次数据增加。
摘要由CSDN通过智能技术生成

1. 安装

npm i vuex -s

在项目的根目录下新增一个store文件夹,在该文件夹内创建index.js

2. 使用

1、初始化storeindex.js中的内容:

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

//挂载Vuex
Vue.use(Vuex)

//创建VueX对象
const store = new Vuex.Store({
    state:{},
    mutations:{},
    actions:{}
})

export default store

2、在Vue实例上挂载

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

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,  //将创建的Vuex实例挂载到这个vue实例中
  render: h => h(App)
})

3、具体使用

  1. 在组件中使用Vuex中的数据

    <template>
        <div id='app'>
            <h1>{{ $store.state.name }}</h1>
        </div>
    </template>
    

    补充:如果是在方法中使用数据,则是:this.$store.state.name

  2. 修改Vuex中的数据(Mutations)

    mutations是操作state数据的方法的集合,比如对数据的修改、增加、删除。

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    //挂载Vuex
    Vue.use(Vuex)
    
    //创建VueX对象
    const store = new Vuex.Store({
        state:{
            name:'VueX'
        },
        mutations:{
            edit(state){
                state.name = 'Byu'
            },
            
    		//使用Vue.set增删state
            editAge(state, payload) {
    			Vue.set(state, payload)
    		}
        }
    })
    
    export default store
    
  3. 调用mutations中的方法

    this.$store.commit('edit')
    this.$store.commit({
    	type: 'editAge',
    	{age: 18}
    })
    

    Vue.set增删state数据

    使用Vue.set增删state中的成员,增删的对象{age: 18},在调用mutations中的editAge方法时,以参数的形式传入。

    在store中的mutations里,传入的参数又被payload参数接收,所以在mutations里Vue.set(state, payload)payload等于{age: 18}

  4. Mutation传参

    单个参数

    this.$store.commit('edit',15)
    

    多个参数

    this.$store.commit('edit',{age:15,sex:'男'})
    
  5. Actions —— 异步操作

    Actions方法中有两个默认参数:context 上下文(相当于箭头函数中的this)对象;payload 挂载参数。

    actions:{
        aEdit(context,payload){
            setTimeout(()=>{
                context.commit('edit',payload)
            },2000)
        }
    }   
    

    如上,aEdit方法中的setTimeout是异步操作,所以需要使用actions

  6. 调用Actions中的方法

    this.$store.dispatch('aEdit',{age:15})
    

    count每隔两秒进行一次增加

    state: {
    	count: 1
    },
    mutations: {
    	add(state){
    	   	state.count++
    	}
    },
    actions:{
        aAdd(context){
            setInterval(()=>{
                context.commit('add')
            },2000)
        }
    }   
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值