uni-app-使用状态管理Vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

Vuex 是专门为 Vue.js 设计的状态管理库,以利用 Vue.js 的细粒度数据响应机制来进行高效的状态更新

uni-app 内置了 Vuex,不需要去安装,直接导入使用。

1、在 uni-app 项目根目录下,新建 store 目录,在此目录下新建 index.js 文件。在 index.js 文件配置如下:

// 页面路径:store/index.js 
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex); //vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	//存放状态
	state: {
		//更多精品图片宽度
		moreImgWidth: null

	},
	// getters, 等同于 store.getters---全局的计算属性
	getters: {

	},
	// Vuex中store数据改变的唯一方法就是mutation---修改数据的方法
	mutations: {
		getMoreImgWidth(state, e) {
			state.moreImgWidth = e;

		}
	},
	// 全局操作的方法
	actions: {

	}
})
export default store

在这里插入图片描述

2、在 main.js中导入文件

// 页面路径:main.js
import Vue from 'vue'
import App from './App'
import store from './store'

Vue.prototype.$store = store

// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
const app = new Vue({
	store,
	...App
})
app.$mount()


3、页面中使用

	import { mapState,mapMutations } from 'vuex';
	computed: {
			...mapState(['moreImgWidth'])
		},
<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		name: "MoreGoods",

		data() {
			return {
			};

		},
		computed: {
			...mapState(['moreImgWidth'])
		},

	}
</script>

this.$store.commit('getMoreImgWidth', this.moreImgWidth);

取:因为 computed: { ...mapState(['moreImgWidth']) },可直接在页面使用moreImgWidth

猜你喜欢

转载自blog.csdn.net/m0_48259951/article/details/129836051
今日推荐