vuex的学习笔记(uni app)1

本文介绍了如何在一周内学习Vuex,包括理解Vuex在组件状态管理中的作用,安装与导入Vuex,创建store,将store挂载到Vue实例,以及在组件中通过不同方式获取store数据。内容涵盖了在main.js中配置store,以及在模板和计算属性中使用state数据的三种方法。
摘要由CSDN通过智能技术生成

学习目标:

  • 一周掌握 vuex入门知识

学习内容:

1.Vuex 是实现组件状态(数据)管理的一种机制,可以方便实现组件之间的数据共享,即把需要共享的数据存放在vuex中。
2.安装vuex依赖包
3.导入vuex包
4.创建store对象

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

import App from './App'

// #ifndef VUE3
import Vue from 'vue'
import store from './store'

Vue.prototype.$store = store

Vue.config.productionTip = false

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

// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  return {
    app
  }
}
// #endif

在main.js 中导入store

// 页面路径: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()

5.将store对象挂载到vue实例中

获取store数据

<template>
	<view class="content">
		<text> 用户名:{{username}}</text>
		<text>年龄:{{age}}</text>
		</view>
	</view>
</template>

第一种方法:通过属性访问,需要在根节点注入 store

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

第二种方法:在组件中使用,通过 this.$store 访问到 state 里的数据

<script>
	export default {
		data() {
			return {}
		},
		computed: {
			username() {
				return this.$store.state.username 
			}
		}
	}
</script>

第三种方法:通过mapState辅助函数帮忙生成计算属性

<script>
	import { mapState } from 'vuex'//引入mapState
	export default {
		data() {
			return {}
		},
		computed: mapState({
		    // 从state中拿到数据 箭头函数可使代码更简练
		    username: state => state.username,
			age: state => state.age,
		}) 
	}
</script>

5.为了能够使用 this 获取组件自己的data数据,必须使用常规函数

<template>
	<view>
		<view>用户名:{{username}}</view>
		<view>年龄:{{age}}</view>
	</view>
</template>
<script>
	import { mapState } from 'vuex'//引入mapState
	export default {
		data() {
			return {
				firstName:"Li"
			}
		},	
		computed: {
			...mapState({
				username: function (state) {
				    return this.firstName 
				},
				age: state => state.age,
			})
		},
	}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值