uniapp使用vuex

该博客介绍了如何在uniapp项目中集成并使用Vuex。首先,uniapp提供了内置的Vuex插件,可以直接引入。接着,通过在项目中创建store文件夹并在main.js中导入挂载Vuex。在store目录下创建index.js,并在main.js中进行配置。最后,文中提到了两种使用Vuex的方法:一是直接通过`this.$store`操作;二是利用`mapState`, `mapGetters`, `mapActions`, `mapMutations`进行状态管理和操作。" 80614324,7217915,Oracle 数据导出与导入详解,"['数据库管理', 'Oracle数据库', '数据迁移']

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

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

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

 

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)
// 方法1(直接写)
const store = new Vuex.Store({
    state: {
		//公共的变量,这里的变量不能随便修改,只能通过触发mutations的方法才能改变
	    text1: 1
    },
    getters: {
        // state的计算属性
        get1: state => {
            return state.text1 + 1
        },
        get2: (state, getters) => {
            //state :可以访问数据
            //getters:访问其他函数,等同于 store.getters
            return getters.get1
        },
        getTodoById: (state) => (value) => {
            return state.text1 + value
        }
    },
    mutations: {
		//相当于同步的操作
        //传递数值
        add(state, n) {
            state.text1 += n
        }
        //传递对象类型
        add(state, payload) {
            state.text1 += payload.value
        }
	},
    actions: {
		//相当于异步的操作,不能直接改变state的值,只能通过触发mutations的方法才能改变
        addCountAction (context , payload) {
            context.commit('add',payload)
        }
	}
})
export default store
// 方法二(分模块)
// 如果将store分成一个个的模块的话,则需要用到modules。
//然后在每一个module中写state, getters, mutations, actions等。
import cart from '@/store/modules/cart.js'
export default new Vuex.Store({
	
	modules:{
		cart
	}
})
  • 在main.js中导入挂载vuex

 

三、使用

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

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

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

<script>
    import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
    import store from '@/store/index.js';
//导入
    export default {
        data() {
            return {
            }
        },
        computed: { 
//computed中注册
            ...mapGetters(['get1']),
// 不用modules对应写法
            ...mapState([
                'text1'
            ])
// 用modules对应写法
            ...mapState({
				text1:state=>state.cart.text1
			})
        }
        methods: {
            ...mapMutations(['add']),
            ...mapActions(['addCountAction'])
// 下面示例调用各种方法,就直接用store了
// getters
            this.$store.getters.get1
// mutations
            store.commit('add')
// actions   以对象形式分发
            store.dispatch({
                type: 'addCountAction',
                amount: 5
            })
        }
    }
</script>

<style>
</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值