uniapp中引入VueX

uniapp中方内置 vuex,所以 不需要 npm下载,直接引用就行。

1. 在根目录上新建 store 目录,并在此目录下新建 store.js 文件,在此文件下写如下代码:

// 1. 导入 Vue 和 Vuex
import Vue from "vue"
import Vuex from "vuex"
 
 
// 2. 将 Vuex 安装为 Vue 的插件
Vue.use(Vuex)
 
// 3. 创建 Store 的实例对象
const store = new Vuex.Store({
    
    
// 挂载 store 模块
    modules:{
    
    }
})
 
// 向外共享 Store 的实例对象
export default store

2.在 main.js 中导入 store 实例对象并挂载到 Vue 的实例上:

// 1. 导入 store 的实例对象
import store from './store/store.js'
 
// 省略其它代码...
 
const app = new Vue({
    
    
  ...App,
  // 2. 将 store 挂载到 Vue 实例上
  store,
})
app.$mount()

这样既可使用。

3. VueX的使用

3.1 直接使用

<template>
  <view>
    <text>{
    
    {
    
     count }}</text>
    <button @click="incrementCount">增加</button>
  </view>
</template>

<script>
export default {
    
    
  computed: {
    
    
    // 通过计算属性将 state 中的 count 映射到组件
    count() {
    
    
      return this.$store.state.count;
    },
  },
  methods: {
    
    
    // 触发 action 来增加计数
    incrementCount() {
    
    
      this.$store.dispatch('increment');
    },
  },
};
</script>

在上述代码中,我们使用computed属性将VueX中的count状态映射到组件的数据 count 中,这样当count发生变化时,页面会自动更新。在methods中,我们使用$store.dispatch来触发VueX的increment action。

通过以上步骤,你就可以在Uni-app中使用VueX来进行状态管理了。通过Vuex的状态管理机制,可以方便地在组件之间共享和修改数据。

3.2 使用 map 映射

在Uni-app中,你可以使用VueX提供的mapState、mapGetters、mapMutations和mapActions辅助函数来简化对VueX状态的映射。这些辅助函数可以帮助你在组件中更方便地引入和使用VueX中的状态、getters、mutations和actions。

以下是在Uni-app中使用mapState、mapGetters、mapMutations和mapActions的步骤:

1. 导入需要的辅助函数。

// 在组件的script标签中导入
import {
    
     mapState, mapGetters, mapMutations, mapActions } from 'vuex';

2. 在组件的computed属性中使用mapState将VueX中的状态映射到组件的计算属性。

computed: {
    
    
  ...mapState({
    
    
    count: state => state.count,
    // 其他需要的状态
  }),
}

在上述代码中,我们使用mapState函数将VueX中的count状态映射到组件的count计算属性中。这样,在页面中就可以直接使用this.count来获取VueX中的count状态。

3. 在组件的computed属性中使用mapGetters将VueX中的getters映射到组件的计算属性。

computed: {
    
    
  ...mapGetters([
    'completedTodos',
    // 其他需要的getters
  ]),
}

在上述代码中,我们使用mapGetters函数将VueX中的completedTodos getter映射到组件的计算属性中。这样,在页面中就可以直接使用this.completedTodos来获取VueX中的completedTodos getter。

4. 在组件的methods属性中使用mapMutations将VueX中的mutations映射为组件的方法。

methods: {
    
    
  ...mapMutations([
    'increment',
    // 其他需要的mutations
  ]),
}

在上述代码中,我们使用mapMutations函数将VueX中的increment mutation映射为组件的方法。这样,在页面中就可以直接使用this.increment()来触发VueX中的increment mutation。

5. 在组件的methods属性中使用mapActions将VueX中的actions映射为组件的方法。

methods: {
    
    
  ...mapActions([
    'fetchData',
    // 其他需要的actions
  ]),
}

在上述代码中,我们使用mapActions函数将VueX中的fetchData action映射为组件的方法。这样,在页面中就可以直接使用this.fetchData()来触发VueX中的fetchData action。

通过以上步骤,你可以在Uni-app中使用mapState、mapGetters、mapMutations和mapActions来简化对VueX状态的映射和使用,提高开发效率。

猜你喜欢

转载自blog.csdn.net/weixin_53156345/article/details/132047430