手写vuex源码
发布日期:2021-05-13 22:21:40 浏览次数:15 分类:精选文章

本文共 1646 字,大约阅读时间需要 5 分钟。

一、项目准备

创建一个 Vue 项目

  • 创建项目
    • 使用 vue create componentName 命令创建新项目
  • 进入项目 -چار井到项目文件夹:cd componentName
  • 安装 Vuex -使用 vue add vuex 安装 Vuex 插件
  • vue add vuex

    2. 手写 Vuex

    本 Ottaway 结构需要暴露一个包含 Store 和 install 的对象,所以我们需要自定义 Vue 插件实现手写 Vuex

    // store/vuex.js
    export class Store {
    constructor(options) {
    this._mutations = options.mutations
    this._actions = options.actions
    this._wrappedGetters = options.getters
    this.getters = {}
    this._vm = new Vue({
    data: { $$state: options.state }
    })
    // 定义 computed 状态
    this.computed = []
    this._wrappedGetters.forEach((getter, key) => {
    this.computed[key] = () => {
    return getter(this.state)
    }
    Object.defineProperty(this.getters, key, {
    get: () => this._vm[key]
    })
    })
    }
    get state() {
    return this._vm.data.$$state
    }
    set state(v) {
    console.warn('请使用 replaceState 重置状态')
    }
    commit(type, payload) {
    if (this._mutations[type]) {
    this._mutations[type](this.state, payload)
    }
    }
    dispatch(type, payload) {
    if (this._actions[type]) {
    this._actions[type](this, payload)
    }
    }
    }
    export function install(Vue) {
    Vue.mixin({
    beforeCreate() {
    if (this.$options.store) {
    Vue.prototype.$store = this.$options.store
    }
    }
    })
    }

    3. 整体代码

    完整的自定义 Vuex 插件代码:

    // store/vuex.js
    export { Store, install } from './vuex'
    # App.vue 中使用
    # 安装插件
    在 Vue 创建过程中添加插件:
    ```bash
    vue add vuex

    然后在 main.js 中使用自定义插件:

    import { install } from '../store/vuex'
    new Vue({
    store: new Store({
    # 你的 Vuex 配置
    }),
    install
    })
    上一篇:分析vue2.6.12源码
    下一篇:手写vue-router源码

    发表评论

    最新留言

    路过按个爪印,很不错,赞一个!
    [***.219.124.196]2025年04月19日 00时00分12秒