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>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐