Vuex基本用法介绍

Vuex 是 Vue.js 官方推出的状态管理库,用于管理复杂应用中的全局状态。Vuex 的基本用法包括:

  1. 创建一个 store,定义状态、获取器、mutations 和 actions。

  2. 在 Vue 应用中挂载 store。

  3. 在组件中通过 this.$store 或辅助函数访问和操作状态。

通过 Vuex,可以有效地管理复杂应用中的全局状态,使状态的变化更加可控和可预测。

以下是 Vuex 的基本用法:

1. 安装 Vuex

如果你使用的是 Vue 2,可以直接通过 npm 安装 Vuex:

npm install vuex

如果你使用的是 Vue 3,Vuex 4.x 是专门为 Vue 3 设计的:

npm install vuex@next

2. 创建 Vuex Store

创建一个 store 文件夹,并在其中创建 index.js 文件:

import { createStore } from 'vuex';

// 创建一个 store
const store = createStore({
  // 状态
  state() {
    return {
      count: 0,
      todos: []
    };
  },
  // 获取器
  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  },
  // 修改状态的方法(必须是同步的)
  mutations: {
    increment(state) {
      state.count++;
    },
    decrement(state) {
      state.count--;
    },
    setTodos(state, todos) {
      state.todos = todos;
    }
  },
  // 异步操作
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 1000);
    },
    decrementAsync({ commit }) {
      setTimeout(() => {
        commit('decrement');
      }, 1000);
    },
    fetchTodos({ commit }) {
      // 模拟异步请求
      fetch('https://jsonplaceholder.typicode.com/todos?_limit=5')
        .then(response => response.json())
        .then(todos => {
          commit('setTodos', todos);
        });
    }
  },
  // 模块
  modules: {
    // 可以在这里定义模块
  }
});

export default store;

3. 在 Vue 应用中使用 Store

在主文件 main.js 中引入并挂载 store:

import { createApp } from 'vue';
import App from './App.vue';
import store from './store';

const app = createApp(App);

// 挂载 store
app.use(store);

app.mount('#app');

4. 在组件中使用 Vuex

访问状态

在组件中可以通过 this.$store.state 访问状态

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
  </div>
</template>

<script>
export default {
  computed: {
    count() {
      return this.$store.state.count;
    },
    doubleCount() {
      return this.$store.getters.doubleCount;
    }
  }
};
</script>
使用辅助函数

Vuex 提供了辅助函数 mapStatemapGettersmapMutationsmapActions,可以简化代码:

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
    <button @click="fetchTodos">Fetch Todos</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['count']),
    ...mapGetters(['doubleCount'])
  },
  methods: {
    ...mapMutations(['increment', 'decrement']),
    ...mapActions(['fetchTodos'])
  }
};
</script>
在组件中分发动作

可以通过 this.$store.dispatch 分发动作:

<template>
  <div>
    <button @click="fetchTodos">Fetch Todos</button>
  </div>
</template>

<script>
export default {
  methods: {
    fetchTodos() {
      this.$store.dispatch('fetchTodos');
    }
  }
};
</script>

5. 完整示例

以下是一个完整的示例,展示了如何在组件中使用 Vuex 的状态、获取器、mutations 和 actions:

<template>
  <div>
    <h1>Vuex 示例</h1>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
    <button @click="incrementAsync">Async Increment</button>
    <button @click="fetchTodos">Fetch Todos</button>
    <ul v-if="todos.length">
      <li v-for="todo in todos" :key="todo.id">
        {{ todo.title }}
      </li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['count', 'todos']),
    ...mapGetters(['doubleCount'])
  },
  methods: {
    ...mapMutations(['increment', 'decrement']),
    ...mapActions(['incrementAsync', 'fetchTodos'])
  }
};
</script>

Vuex 提供的辅助函数 mapStatemapGettersmapMutationsmapActions 主要用于简化组件中对 Vuex store 的状态和方法的访问。通过这些辅助函数,可以更方便地将 store 中的状态和方法映射到组件的计算属性和方法中。以下是这些辅助函数的具体作用和用法:

1. mapState

用于将 store 中的状态映射到组件的计算属性中。

语法:
import { mapState } from 'vuex';

export default {
  computed: {
    ...mapState(['state1', 'state2']),
    ...mapState({
      customName: state => state.originalName
    })
  }
};
示例:
import { mapState } from 'vuex';

export default {
  computed: {
    ...mapState(['count', 'todos']),
    ...mapState({
      doubleCount: state => state.count * 2
    })
  }
};

2. mapGetters

用于将 store 中的 getters 映射到组件的计算属性中。

语法:
import { mapGetters } from 'vuex';

export default {
  computed: {
    ...mapGetters(['getter1', 'getter2']),
    ...mapGetters({
      customGetter: 'originalGetter'
    })
  }
};
示例:
import { mapGetters } from 'vuex';

export default {
  computed: {
    ...mapGetters(['doubleCount', 'filteredTodos']),
    ...mapGetters({
      customDoubleCount: 'doubleCount'
    })
  }
};

3. mapMutations

用于将 store 中的 mutations 映射到组件的方法中。

语法:
import { mapMutations } from 'vuex';

export default {
  methods: {
    ...mapMutations(['mutation1', 'mutation2']),
    ...mapMutations({
      customMutation: 'originalMutation'
    })
  }
};
示例:
import { mapMutations } from 'vuex';

export default {
  methods: {
    ...mapMutations(['increment', 'decrement']),
    ...mapMutations({
      customIncrement: 'increment'
    })
  }
};

4. mapActions

用于将 store 中的 actions 映射到组件的方法中。

语法:
import { mapActions } from 'vuex';

export default {
  methods: {
    ...mapActions(['action1', 'action2']),
    ...mapActions({
      customAction: 'originalAction'
    })
  }
};
示例:
import { mapActions } from 'vuex';

export default {
  methods: {
    ...mapActions(['fetchTodos', 'incrementAsync']),
    ...mapActions({
      customFetchTodos: 'fetchTodos'
    })
  }
};

总结

  • **mapState**:将 store 中的状态映射到组件的计算属性中。

  • **mapGetters**:将 store 中的 getters 映射到组件的计算属性中。

  • **mapMutations**:将 store 中的 mutations 映射到组件的方法中。

  • **mapActions**:将 store 中的 actions 映射到组件的方法中。

这些辅助函数的主要作用是简化代码,避免在组件中重复书写 this.$store.statethis.$store.gettersthis.$store.committhis.$store.dispatch,使组件代码更加简洁和易读。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值