uniapp中使用vuex

本文介绍了如何在uniapp中集成和使用Vuex,包括创建store文件夹、导入Vuex、定义state、mutations、actions,以及在组件中通过this.$store访问状态和使用mapState、mapGetters、mapActions、mapMutations进行状态管理和操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

uniapp中使用vuex

一、uniapp中有自带vuex插件,直接引用即可
二、在项目中新建文件夹store,在main.js中导入

  • 在根目录下新建文件夹store,在此目录下新建index.js文件
    在这里插入图片描述
  • index.js
import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
		//公共的变量,这里的变量不能随便修改,只能通过触发mutations的方法才能改变
	},
    mutations: {
		//相当于同步的操作
	},
    actions: {
		//相当于异步的操作,不能直接改变state的值,只能通过触发mutations的方法才能改变
	}
})
export default store
  • 在main.js中导入挂载vuex
import Vue from 'vue'
import App from './App'
import store from './pages/store/index.js'
Vue.prototype.$store = store


Vue.config.productionTip = false

App.mpType = 'app'

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

三、使用

  • 第一种方式:this.$store直接操作

例如当取值:直接在页面中使用this.$store.state.变量名

  • 第二种方法:mapState, mapGetters, mapActions, mapMutations
<template>
    <view class="content">
    
    </view>
</template>

<script>
    import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
    //导入
    export default {
        data() {
            return {
            }
        },
        computed: { //computed中注册
            ...mapGetters(['text1']),
            ...mapState([
                'text1'
            ])
        }
        methods: {
            ...mapMutations([]),
            ...mapActions([])
        }
    }
</script>

<style>
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Smile_zxx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值