Vuex状态管理二——基本使用

399 阅读2分钟

什么是Vuex

  • Vuex是专门为Vue.js设计的状态管理库
  • Vuex采用集中式的方式存储需要共享的状态
  • Vuex的作用是进行状态管理,解决复杂组件通信,数据共享
  • Vuex集成到了devtools中,提供了time-travel时光旅行历史回滚功能

什么情况下使用Vuex

  • 非必要的情况不要使用Vuex (小型项目)
  • 大型的单页面应用程序(多个视图依赖于同一状态,来自不同视图的行为需要变更同一状态)

Vuex核心概念

  • Store:仓库(Vuex核心每一个应用仅有一个Store, Store是一个容器,包含着应用中大部门状态,当然我们不能直接改变Store的状态,需要提交mutation来改变状态)
  • State:状态(保存在Store中,因为Store是唯一的,State也是唯一的,如果状态太多后期使用moudle)
  • Getter:像是vue中的computed的计算属性
  • Mutation:状态的提交必须通过Mutation来提交
  • Action:和Mutation类似,不同的是Action可以进行异步的操作,然后提交Mutation来改变状态
  • Module: 当项目变的庞大,需要用Module

Vuex在vue2.0的用法

vuex.vuejs.org/zh/guide/

Vuex在vue3.0的用法

store/index.ts
import { createStore } from 'vuex';
import products from './modules/products';
import cart from './modules/cart';

export default createStore({
  strict: true,  // 严格模式,不要在生产环境下开启,会响应性能
  state: {
    count: 0,
    msg: 'Hello World!'
  },
  getters: {
    reverseMsg (state) {
      return state.msg.split('').reverse().join('');
    }
  },
  mutations: {
    increate(state, payload: number) {
      state.count += payload
    }
  },
  actions: { 
    // 模拟异步操作
    increateAsync(context, payload: number) {
      setTimeout(() => {
        context.commit('increate', payload)
      }, 2000)
    }
  },
  modules: {
    products,
    cart
  },
});

// index.vue
<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <!-- <HelloWorld msg="Welcome to Your Vue.js + TypeScript App"/> -->
    <!-- count: {{ $store.state.count }}
    msg: {{ $store.state.msg }} -->

    count: {{ count }}
    msg: {{ msg }}
    reverseMsg: {{ reverseMsg }}

    <h2>Mutation</h2>
    <!-- <button @click="$store.commit('increate', 2)">Mutation</button> -->
    <button @click="increate(2)">Mutation</button>

    <h2>Actions</h2>
    <!-- <button @click="$store.dispatch('increateAsync', 5)">Actions(等待2秒)</button> -->
    <button @click="increateAsync(10)">Actions(等待2秒)</button>

    <h2>Module</h2>
    <!-- products: {{ $store.state.products.products }} <br> -->
    products: {{ products.products }}
  
    <button @click="setProducts([])">Mutation</button>
    <button @click="setProducts2([])">Mutation</button>

    <h2>strict</h2>
    // 如果在严格模式下,以下事件会报错
    //  [vuex] do not mutate vuex store state outside mutation handlers.
    <button @click="msg = 'Lagou'">strict</button>


  </div>
</template>

<script lang="ts">
import { defineComponent, toRefs } from 'vue';
// 方法一:
// import $store from '../store/index'
// 方法二:
import { useStore, mapMutations, mapActions } from 'vuex';
//, mapActions, mapState
// import HelloWorld from '@/components/HelloWorld.vue'; // @ is an alias to /src

export default defineComponent({
  name: '',
  // conmponents: {HelloWorld},

  setup(){
    // 方法一
    // let count = computed(() => { return $store.state.count});
    // let msg = computed(() => { return $store.state.msg});
    // 以下是方法二
    const store = useStore();
    const { count, msg, products } = toRefs(store.state);  // products 拿到的是products中state的整个对象
    const {reverseMsg} = toRefs(store.getters);
    const { increate } = mapMutations(['increate']);
    const { increateAsync } = mapActions(['increateAsync']);
    // console.log(store);
    
    // module
    const { setProducts, setProducts2 } = mapMutations('products', ['setProducts', 'setProducts2']);
    
    
    return {
      count,
      msg,
      reverseMsg,
      increate,
      increateAsync,
      products,
      setProducts,
      setProducts2
    }
  }
})
</script>