[保姆级教程]uniapp配置vueX

发布于:2024-06-26 ⋅ 阅读:(19) ⋅ 点赞:(0)

在这里插入图片描述


注意

uniapp是支持vueX的只需配置一下就好

新建文件

在src文件中,新建一个store(如果有的话跳过)
在这里插入图片描述
在store中新建一个js文件,修改js文件名称和选择模板为default
在这里插入图片描述
在 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:{//存放状态
		"username":"foo",
		"age":18
	}
})
export default store

在这里插入图片描述
在 main.js 中导入文件

import store from './store'

Vue.prototype.$store = store

const app = new Vue({
	store,
	...App
})

在这里插入图片描述

简单的使用

通过属性访问,需要在根节点注入 store 。

<template>
	<view>
		<text>用户名:{{username}}</text>
	</view>
</template>
<script>
	import store from '@/store/index.js';//需要引入store
	export default {
		data() {
			return {}
		},
		computed: {
			username() {
				return store.state.username 
			}
		}
	}
</script>

在组件中使用,通过 this.$store 访问到 state 里的数据。

<template>
	<view>
		<text>用户名:{{username}}</text>
	</view>
</template>
<script>
	export default {
		data() {
			return {}
		},
		computed: {
			username() {
				return this.$store.state.username 
			}
		}
	}
</script>

您好,我是肥晨。
欢迎关注我获取前端学习资源,日常分享技术变革,生存法则;行业内幕,洞察先机。