uniapp vue3中vuex的使用

本文介绍了如何在Vue应用中使用Vuex进行状态管理,包括创建store、配置state、组件间通信及在SSR中的应用。从新建store文件、定义初始状态到在页面上读取状态,一步步带你理解Vuex的实践过程。

  首先在根目录下新建一个store文件夹,并在其中创建index.js,然后引入vuex

这只是使用vuex的一种方法,简单调用一下

import { createStore } from 'vuex'
const store = createStore({
    state:{//存放状态
        "username":"狐狸",
        "age":18
    }
})

export default store

 在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
  }
}

 在页面中调用

<template>
	<view class="content">
		{{username}}
	</view>
</template>

<script>
	import store from '@/store/index.js'; //需要引入store
	import {
		computed,
		reactive,
		watchEffect
	} from "vue";

	export default {
		data() {
			return {
				title: 'Hello',
				vuexMsg: ''
			}
		},
		onLoad() {
			
		},
		methods: {

		},
		setup() {
			let username = computed(() => {
				return store.state.username
			})

			return {
				username
			}
		}
	}
</script>

uniApp是一个基于Vue.js的跨平台框架,用于快速构建原生移动应用。在Vue3版本中,VuexVue的状态管理工具)仍然可以作为核心组件来管理和共享应用程序的状态。以下是uniApp中如何使用Vuex的基本步骤: 1. 安装Vuex:首先需要安装`vue3-element-ui-vuex`或者`vuex`库,如果你使用的是基于Element Plus的架构,推荐后者。 ```bash npm install vuex --save ``` 2. 初始化Store:在项目中创建一个名为store的文件夹,并在其中创建一个index.js文件,配置初始状态(state)、 mutations、actions 和 getters。 ```javascript import { createStore } from &#39;vuex&#39; const state = { count: 0, } const mutations = { increment(state) { state.count++ }, } const actions = { increment(context) { context.commit(&#39;increment&#39;) }, } const getters = { getCount(state) { return state.count }, } export default createStore({ state, mutations, actions, getters, }) ``` 3. 使用Store:在每个需要访问或修改状态的组件中,通过`mapState`、`mapGetters`、`mapActions`和`mapMutations`来自动导入和使用状态和方法。 ```javascript <template> <div>{{ count }}</div> <button @click="increment">点击加一</button> </template> <script> import { mapState, mapActions } from &#39;vuex&#39; export default { computed: { ...mapState([&#39;count&#39;]), // 获取状态 }, methods: { ...mapActions([&#39;increment&#39;]), // 调用动作 increment() { this.increment() }, }, } </script> ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值