uni-app-使用状态管理Vuex

6 篇文章 0 订阅

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值