优秀的编程知识分享平台

网站首页 > 技术文章 正文

Vuex基本使用(vuex的基本使用)

nanyue 2024-10-02 17:48:22 技术文章 9 ℃

1 安装vuex

npm install vuex -S

2 导入vuex

import Vuex from "vuex"

Vue.use(Vuex)

创建store对象

const store = new Vuex.Stroe({
	state : {
		count : 0
	}
});

4将store对象挂载到vue实例中

new Vue({
	el : '#app'
	render: h => h(app),
	router,
	store
})

主要核心概念

  • State
  • Mutation
  • Action
  • Getter

State

State提供唯一的公共数据源, 所有共享的数据都要统一放到Store的State中存储

const store = new Vuex.Stroe({
	state : {count : 0}
});

组件中访问State中数据的第一种方式

this.$store.state.全局数据名称

组件中访问State中数据的第二种方式

// 从vuex中导入mapState函数
import {mapState} from 'vuex

通过导入mapState函数, 将当前组件需要的全局数据 映射为当前组件的computed计算属性

computed: {
	...mapState(['count'])
}

Mutaion

mutaion用于变更store中的数据

  • 只能通过mutation变更Store中的数据, 不可以直接操作Store中的数据
  • 通过这种方式虽然操作起来繁琐一些,但是可以集中监控所有数据的变化
// 定义mutation
const store = new Vuex.Store({
	state : {count: 0},
	mutations: {
		add(state){
			state.count++
		}
	}
})

//触发mutation
methods: {
  handler(){
    this.$store.commit('add')
  }
}

commit的作用就是调用某个mutation

mutatitons传递参数

mutations:{
	//定义
	addN(state, step){
		state.count += step
	}
}

//触发mutation
methods: {
  handler(){
    //触发时携带参数
    this.$store.commit('addN', 3)
  }
}

触发mutations的第二种方式

//从vuex中按需导入mapMutations函数
import {mapMutations} from 'vuex'

通过导入的mapMutations函数,将需要的函数映射为当前组件的methods

methods: {
	...mapMutations(['add', 'addN'])
}

//调用
this.addN(3)

Action

Action用于处理异步任务

如果通过异步操作变更数据,必须通过Action,而不能使用mutation,但是在Action中还是通过触发mutaion的方式间接变更数据

const store = new Vuex.Store({
  // 只有mutations中定义的函数才能修改state的数据
	mutations : {
		add(state){
			state.count ++;
		}
	},
	actions:{
		addAsync(context){
      // 在action中不能直接修改sate中的数据,必须通过context.commit()触发mutation
			setTimeout(() => {
				context.commit('add')
			}, 1000);
		}
	}
})


//触发action
methods: {
  handler(): {
    this.$store.dispatch('addAsync')
  }
}

触发actions携带参数

const store = new Vuex.Store({
	state: {count: 0},
	mutations: {
		addN(state, step){
			state.count += step
		}
	},
	actions:{
		addNAsync(context, step){
			setTimeout(() => {
				context.commit('addN', step)
			}, 1000)
		}
	}
})

//触发action
methods: {
	handle(){
		this.$store.dispatch('addNAsync', 5)
	}
}

Getter

getter 用于对store中的数据进行加工处理形成新的数据

  • getter可以对store中已有的数据进行加工处理形成行的数据, 类似Vue的计算属性
  • store中的数据发生变化 getter中的数据也会发生相应的变化
//定义getter
const store = new Vuex.Store({
	state : {count: 0},
	getters: {
		showNUm(state){
			return '当前最新的数据是' +state.count;
		}
	}
});

使用Getter的方式 一

this.$store.getters.showNUm

第二种方式

import {mapGetters} from 'vuex'

computed: {
	...mapGetters(['showNum'])
}
最近发表
标签列表