uni-app 框架中使用 vuex(store)

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

uni-app 内置了 Vuex,不需要额外安装。

使用步骤如下:

1、项目根目录下新建 store/index.js

vue2 写法

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
    
    
  state: {
    
    }, 
  mutations: {
    
    },
  actions: {
    
    },
  // ....
)

export default store

vue3写法

import {
    
     createStore } from 'vuex'

const store = createStore({
    
    
  state: {
    
    },
  mutations: {
    
    },
  actions: {
    
    },
  // ....
})

export default store

2、配置 main.js

vue2 写法

// 引入vuex,并且挂载到 vue 实例上
import store from './store/index.js'
Vue.prototype.$store = store

vue3写法

import Store from './store' // 在最顶部引入vuex

// #ifdef VUE3
import {
    
     createSSRApp } from 'vue'
export function createApp() {
    
    
  const app = createSSRApp(App)
  app.use(Store) // use使用
  return {
    
    
    app
  }
}
// #endif

3、使用(示例)

// 使用store中的变量
this.$store.state.token


import {
    
     mapActions } from 'vuex'
export default {
    
    
  methods: {
    
    
    // 映射 this.Login() 为 this.$store.dispatch('Login')
    ...mapActions(['Login']),
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_45559449/article/details/133138667