关于vue3:一起学习Vuex-40的状态管理Vite

6次阅读

共计 9890 个字符,预计需要花费 25 分钟才能阅读完成。

本文目录

  1. 简略介绍 vite, 搭建 vite 我的项目。
  2. 装置 vuex
  3. Vuex 根底介绍
  4. 应用 Vuex
  5. 插件引入

    1. 简略介绍 vite, 搭建 vite 我的项目

    1.1 什么是 vite?

    Vite 是一种新型前端构建工具,可能显著晋升前端开发体验。它次要由两局部组成:

  6. 一个开发服务器,它基于 原生 ES 模块 提供了 丰盛的内建性能,如速度快到惊人的 模块热更新(HMR)。
  7. 一套构建指令,它应用 Rollup 打包你的代码,并且它是预配置的,可输入用于生产环境的高度优化过的动态资源。

Vite 意在提供开箱即用的配置,同时它的 插件 API 和 JavaScript API 带来了高度的可扩展性,并有残缺的类型反对。
Vite 将会应用 esbuild 预构建依赖。Esbuild 应用 Go 编写,并且比以 JavaScript 编写的打包器预构建依赖快 10-100 倍。

1.2 初始化 vite

npm init vite@latest

1.3 新建第一个 vite 我的项目

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

2. 装置 vuex

npm install vuex@next --save

3.Vuex 根底介绍

3.1 vuex

每一个 Vuex 利用的外围就是 store(仓库)。“store”基本上就是一个容器,它蕴含着你的利用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:

Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地失去高效更新。

你不能间接扭转 store 中的状态。扭转 store 中的状态的惟一路径就是显式地提交 (commit) mutation。这样使得咱们能够不便地跟踪每一个状态的变动,从而让咱们可能实现一些工具帮忙咱们更好地理解咱们的利用。

次要蕴含五个局部:State、Getters、Mutations、Actions、Module。

3.1.1 State 概念

Vuex 应用繁多状态树——是的,用一个对象就蕴含了全副的利用层级状态。至此它便作为一个“惟一数据源 (SSOT)”而存在。这也意味着,每个利用将仅仅蕴含一个 store 实例。繁多状态树让咱们可能间接地定位任一特定的状态片段,在调试的过程中也能轻易地获得整个以后利用状态的快照。

3.1.2 宰割模块(module)

因为应用繁多状态树,利用的所有状态会集中到一个比拟大的对象。当利用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 容许咱们将 store 宰割成模块(module)。每个模块领有本人的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样形式的宰割:由此此处宰割为两个状态治理模块。(test 和 test1 模块)。

//store/test.js
export const test = {
    namespaced: true,
    state: {
        name: '叫我詹躲躲',
        gender: '男',
        profession: '前端开发',
        age: 10
    }
}

//store/test1.js
export const test1 = {
    namespaced: true,
    state: {
        name: '二月',
        sport: '跑步、代码和音乐',
        publics:'叫我詹躲躲',
        amount:100
    },
}

3.1.3 命名空间(namespaced)

默认状况下,模块外部的 action 和 mutation 依然是注册在全局命名空间的——这样使得多个模块可能对同一个 action 或 mutation 作出响应。Getter 同样也默认注册在全局命名空间,然而目前这并非出于性能上的目标(仅仅是维持现状来防止非兼容性变更)。必须留神,不要在不同的、无命名空间的模块中定义两个雷同的 getter 从而导致谬误。
如果心愿你的模块具备更高的封装度和复用性,你能够通过增加 namespaced: true 的形式使其成为带命名空间的模块。

3.1.4 Getters 定义

有时候咱们须要从 store 中的 state 中派生出一些状态, 如:

//store/test.js
export const test = {
    namespaced: true,
    state: {
        name: '叫我詹躲躲',
        gender: '男',
        profession: '前端开发',
        age: 10
    },
    // 从 state 派生的一些状态,能够将该局部抽离进去成函数不便调用
    getters: {
        getUserInfo: state => {return state.name + '的职业是' + state.profession},
        getUserSex: state => {return state.name + '的性别是' + state.gender}
    },
}

//store/test1.js
export const test1 = {
    namespaced: true,
    state: {
        name: '二月',
        sport: '跑步、代码和音乐',
        publics:'叫我詹躲躲',
        amount:100
    },
    getters: {
        getSport: state => {return state.name + '喜爱的运行是' + state.sport},
        getPublics: state => {return state.name + '的公众号是' + state.publics}
    },
}

3.1.5.mutations 定义

更改 Vuex 的 store 中的状态的惟一办法是提交 mutation。Vuex 中的 mutation 十分相似于事件:每个 mutation 都有一个字符串的事件类型 (type) 和一个回调函数 (handler)。这个回调函数就是咱们理论进行状态更改的中央,并且它会承受 state 作为第一个参数:

//store/test.js
export const test = {
    namespaced: true,
    state: {
        name: '叫我詹躲躲',
        gender: '男',
        profession: '前端开发',
        age: 10
    },
    // 从 state 派生的一些状态,能够将该局部抽离进去成函数不便调用
    getters: {
        getUserInfo: state => {return state.name + '的职业是' + state.profession},
        getUserSex: state => {return state.name + '的性别是' + state.gender}
    },
    mutations: {testMutation1(state) {
            // 变更状态
            state.age++;
        },
        // 第二个参数是载荷
        testMutation2(state, payload) {state.age += payload.content;}
    },
}

//store/test1.js
export const test1 = {
    namespaced: true,
    state: {
        name: '二月',
        sport: '跑步、代码和音乐',
        publics:'叫我詹躲躲',
        amount:100
    },
    getters: {
        getSport: state => {return state.name + '喜爱的运行是' + state.sport},
        getPublics: state => {return state.name + '的公众号是' + state.publics}
    },
    mutations: {test1Mutation1(state) {state.amount++;},
        // 第二个参数是载荷
        test1Mutation2(state, payload) {state.amount += payload.amount;}
    },
}

3.1.6.actions 定义

Action 相似于 mutation,不同在于:
Action 提交的是 mutation,而不是间接变更状态。
Action 能够蕴含任意异步操作。

//store/test.js
export const test = {
    namespaced: true,
    state: {
        name: '叫我詹躲躲',
        gender: '男',
        profession: '前端开发',
        age: 10
    },
    // 从 state 派生的一些状态,能够将该局部抽离进去成函数不便调用
    getters: {
        getUserInfo: state => {return state.name + '的职业是' + state.profession},
        getUserSex: state => {return state.name + '的性别是' + state.gender}
    },
    mutations: {testMutation1(state) {
            // 变更状态
            state.age++;
        },
        // 第二个参数是载荷
        testMutation2(state, payload) {state.age += payload.content;}
    },
    actions: {testAction1(context) {context.commit('testMutation1');
        },
        // 通过参数解构来简化代码,testAction1 简化为 testAction2 写法
        testAction2({commit}, payload) {
            commit({
                type: 'testMutation2',
                content: payload.content
            });
        }
    }
}

//store/test1.js
export const test1 = {
    namespaced: true,
    state: {
        name: '二月',
        sport: '跑步、代码和音乐',
        publics:'叫我詹躲躲',
        amount:100
    },
    getters: {
        getSport: state => {return state.name + '喜爱的运行是' + state.sport},
        getPublics: state => {return state.name + '的公众号是' + state.publics}
    },
    mutations: {test1Mutation1(state) {state.amount++;},
        // 第二个参数是载荷
        test1Mutation2(state, payload) {state.amount += payload.amount;}
    },
    actions: {test1Action1(context) {context.commit('test1Mutation1');
        },
        test1Action2({commit}, payload) {
            commit({
                type: 'test1Mutation1',
                content: payload.content
            });
        }
    }
}

曾经保护了 store 仓库,在组件中应用咱们的状态。

4. 状态应用

4.1 引入

//store/index.js 内容

import {createStore} from "vuex";
import {test} from "./modules/test";
import {test1} from "./modules/test1";

export const store = createStore({
  // Vuex 容许 store 宰割成小的 module, 每个模块领有本人的 state、mutation、action、getter;
  // 拜访 test 的状态:store.state.test
  modules: {
    test, //store 模块 1
    test1 //store 模块 2
  }
});

main.js 应用

//main.js
import {createApp} from 'vue'
import App from './App.vue'
import {store} from './store'
let app = createApp(App)
app.use(store).mount('#app')

4.2 组件中应用状态

4.2.1 应用 state

test 外面的状态

//test 外面的状态
<h3>1.test 模块 state 的状态 </h3>
<h5>{{userName}}</h5>
<h5>{{userInfo}}</h5>

<script setup>
import {computed} from 'vue'
import {useStore} from 'vuex'
const store = useStore()
/* ------------test 模块状态 -----------------*/
// 获取 test1 模块的状态
const userName = computed(() => store.state.test.name)
const userInfo = computed(() => store.state.test.name + '的职业是:' + store.state.test.profession
)
</script>

test1 外面的状态

//test1 外面的状态
<h3>1.test1 模块 state 的状态 </h3>
<h5>{{sport}}</h5>
<h5> 公众号:{{publics}}</h5>

// 获取 test2 模块的状态
const publics = computed(() => store.state.test1.publics)
const sport = computed(() => store.state.test1.name + '喜爱的静止:' + store.state.test1.sport
)

4.2.2 应用 getters

test 模块 getters 的状态

<h3>2.test 模块 getters 的状态 </h3>
<h5>{{getUserInfo}}</h5>
<h5>{{getUserSex}}</h5>

// 获取 getters
const getUserInfo = computed(() => store.getters['test/getUserInfo'])
const getUserSex = computed(() => store.getters['test/getUserSex'])

test1 模块 getters 的状态

<h3>2.test1 模块 getters 的状态 </h3>
<h5>{{getSport}}</h5>
<h5>{{getPublics}}</h5>

// 获取 getters
const getSport = computed(() => store.getters['test1/getSport'])
const getPublics = computed(() => store.getters['test1/getPublics'])

4.2.3 应用 mutations

用 mutations 扭转 test 模块 age 的状态

<h3>3. 用 mutations 扭转 test 模块 age 的状态 </h3>
<button @click="testClick"> 扭转 test 状态(age)</button>
<h5>{{age}}</h5>

// 通过 mutations 扭转状态, 扭转 test 模块的 age
const age = computed(() => store.state.test.age)
const testClick = () => {store.commit('test/testMutation1')
}

用 mutations 扭转 test1 模块 amount 的状态

<h3>3. 用 mutations 扭转 test1 模块 amount 的状态 </h3>
<button @click="test1Click"> 扭转 test1 状态(amount)</button>
<h5>{{amount}}</h5>

// 通过 mutations 扭转状态, 扭转 test1 模块的 amount
const amount = computed(() => store.state.test1.amount)
const test1Click = () => {store.commit('test1/test1Mutation1')
}

4.2.4 应用 actions

用 actions 扭转 test 模块 age 的状态

<h3>4. 用 actions 扭转 test 模块 age 的状态 </h3>
<button @click="changeActions"> 扭转 test 状态(age)</button>
<h5>{{age}}</h5>

// 通过 actions 扭转状态, 扭转 test 模块的 age
const changeActions = () => {store.dispatch('test/testAction1')
}

用 actions 扭转 test1 模块 amount 的状态

<h3>4. 用 actions 扭转 test1 模块 amount 的状态 </h3>
<button @click="changeActions1"> 扭转 test 状态(amount)</button>
<h5>{{amount}}</h5>

// 通过 actions 扭转状态, 扭转 test 模块的 amount
const changeActions1 = () => {store.dispatch('test1/test1Action1')
}

残缺的 Demo 示例

<template>
  <div>
    <h2>Vuex 状态学习 </h2>
    <div class="wrapper">
      <div class="left-box">
        <h3>1.test 模块 state 的状态 </h3>
        <h5>{{userName}}</h5>
        <h5>{{userInfo}}</h5>
        ----------------------------------------------------------
        <h3>2.test 模块 getters 的状态 </h3>
        <h5>{{getUserInfo}}</h5>
        <h5>{{getUserSex}}</h5>
        ----------------------------------------------------------
        <h3>3. 用 mutations 扭转 test 模块 age 的状态 </h3>
        <button @click="testClick"> 扭转 test 状态(age)</button>
        <h5>{{age}}</h5>
        ----------------------------------------------------------
        <h3>4. 用 actions 扭转 test 模块 age 的状态 </h3>
        <button @click="changeActions"> 扭转 test 状态(age)</button>
        <h5>{{age}}</h5>
      </div>

      <div class="line"></div>
      <div class="right-box">
        <h3>1.test1 模块 state 的状态 </h3>
        <h5>{{sport}}</h5>
        <h5> 公众号:{{publics}}</h5>
        ----------------------------------------------------------
        <h3>2.test1 模块 getters 的状态 </h3>
        <h5>{{getSport}}</h5>
        <h5>{{getPublics}}</h5>
        ----------------------------------------------------------
        <h3>3. 用 mutations 扭转 test1 模块 amount 的状态 </h3>
        <button @click="test1Click"> 扭转 test1 状态(amount)</button>
        <h5>{{amount}}</h5>
        ----------------------------------------------------------
        <h3>4. 用 actions 扭转 test1 模块 amount 的状态 </h3>
        <button @click="changeActions1"> 扭转 test 状态(amount)</button>
        <h5>{{amount}}</h5>
      </div>
    </div>

  </div>
</template>
<script setup>
import {computed} from 'vue'
import {useStore} from 'vuex'
const store = useStore()
/* ------------test 模块状态 -----------------*/
// 获取 test1 模块的状态
const userName = computed(() => store.state.test.name)
const userInfo = computed(() => store.state.test.name + '的职业是:' + store.state.test.profession
)
// 获取 getters
const getUserInfo = computed(() => store.getters['test/getUserInfo'])
const getUserSex = computed(() => store.getters['test/getUserSex'])

// 通过 mutations 扭转状态, 扭转 test 模块的 age
const age = computed(() => store.state.test.age)
const testClick = () => {store.commit('test/testMutation1')
}

// 通过 actions 扭转状态, 扭转 test 模块的 age
const changeActions = () => {store.dispatch('test/testAction1')
}

/* -----------test1 模块状态 ------------------*/
// 获取 test2 模块的状态
const publics = computed(() => store.state.test1.publics)
const sport = computed(() => store.state.test1.name + '喜爱的静止:' + store.state.test1.sport
)
// 获取 getters
const getSport = computed(() => store.getters['test1/getSport'])
const getPublics = computed(() => store.getters['test1/getPublics'])

// 通过 mutations 扭转状态, 扭转 test1 模块的 amount
const amount = computed(() => store.state.test1.amount)
const test1Click = () => {store.commit('test1/test1Mutation1')
}

// 通过 actions 扭转状态, 扭转 test 模块的 amount
const changeActions1 = () => {store.dispatch('test1/test1Action1')
}
</script>

<style scoped>
h2 {text-align: center;}
.wrapper {
  width:1200px;
  margin: 0 auto;
}
.left-box,
.right-box {width:calc(50% - 4px);
  display: inline-block;
  text-align: center;
  background: #c4bebf;
  border-radius: 5px;
}
.line {
  height: 100%;
  width: 4px;
  display: inline-block;
}
</style>

5. 插件

Vuex 的 store 承受 plugins 选项,这个选项暴露出每次 mutation 的钩子。Vuex 插件就是一个函数,它接管 store 作为惟一参数:

const myPlugin = (store) => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    // 每次 mutation 之后调用
    // mutation 的格局为 {type, payload}
  })
}

5.1 应用插件

const store = createStore({plugins: [myPlugin]
})

以上是 vuex 的应用和局部参数的解释,每天提高一点点,欢送一起学习交换。我是叫我詹躲躲。文章不定期更新到 集体博客(https://zhanhongzhu.top)、掘金、思否和微信公众号【叫我詹躲躲】。一起精进,一起成长。

参考文章

vuex 中文文档:https://vuex.vuejs.org/zh/

正文完
 0