在uni-app(Vue3)中使用Vuex

起因

  在用uni-app开发一个小程序的登录功能的时候,需要使用Vuex管理token值和用户信息方便后面使用,于是就跟着黑马程序员的一个项目实战写,写完后发现报了两个警告,一个错误,如下图:

在这里插入图片描述

反复检查没有敲错之后,百度发现原因也是千奇百怪的,正当写不下去的时候,我又去搜了Vuex的使用方法,发现创建store实例的时候有不同的写法,发现Vue2和Vue3的使用方法原来有所不同,于是我就想起了我使用的正是Vue3,在查阅了uni-app的官方文档后成功解决了这个问题。

解决

  1. 首先创建一个store 文件夹,并在文件夹中创建一个store.js 文件,在文件中输入以下代码:
// 页面路径:store/index.js
import {
    
     createStore } from 'vuex'
const store = createStore({
    
    
	state:{
    
    //存放状态
		"username":"foo",
		"age":18
	}
})

export default store
  1. 接着在 main.js 中导入文件。
// 页面路径:main.js 
import App from './App'
import store from './store'
import {
    
    createSSRApp} from 'vue'
export function createApp() {
    
    
	const app = createSSRApp(App)
	app.use(store)
	return {
    
    
		app
	}
}
  1. 然后就可以使用属性访问辅助函数的方式使用了!(在组件中使用,通过 this.$store 访问到 state 里的数据)
<!-- 页面路径:pages/index/index.vue -->
<template>
	<view>
		<view>用户名:{
    
    {
    
    username}}</view>
		<view>年龄:{
    
    {
    
    age}}</view>
	</view>
</template>
<script>
	import {
    
     mapState } from 'vuex'//引入mapState
	export default {
    
    
		data() {
    
    
			return {
    
    }
		},
		computed: mapState({
    
    
		   // 从state中拿到数据 箭头函数可使代码更简练
		   username: state => state.username,
			age: state => state.age,
		}) 
	}
</script>

总结

  • Vue3和Vue2在创建和引入Vuex的时候有所不同。

  • 碰到Cannot read property 'state' of undefined 的时候报错原因有多种多样,需仔细排查。

猜你喜欢

转载自blog.csdn.net/weixin_57006241/article/details/125922122