npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vuex-cuer

v0.2.4

Published

vuex typescript 的 继承

Downloads

8

Readme

vuex-cuer

简介

还在为 vuex 的魔法字符串而烦恼?还在为阅读项目里 vuex 相关的代码而头痛? 如何一目了然的知道某个 type 的功能?定义字符串常量加以注释 或者 使用d.ts文件进行注释? 那如何快捷的定位到 commitdispatch 相应的type 的原函数? 你可以来试试 vuex-cuer ,纵享丝滑

地址

github  码云  npm 

示例

demo  js中的写法  ts中的写法 

将项目 clone 下来之后执行 npm run dev 即可启动 demo ,当然前提是你已经初始化了。

效果

  1. 推荐直接通过commits调用函数,因为这样有能查看到原函数的注释

    Image text

  2. 兼容commit函数调用,并且优化了提示

    Image text

诞生

  1. 由来

    这个库的诞生是因为我实在受不了接手的这个项目里的 vuex 相关的代码,阅读起来令我头皮发麻 于是我决定使用 Typescript 基于 vuex 来封装一个有类型约束的库。

  2. 结构

    但是在设计之初我遇到了循环引用的问题,场景是:定义一个 store 对象的时候参数有 mutations 等等,然后需要在 mutations 的函数中访问 store 对象,如以下代码:

    const store = new Vuex.Store({
      state: {
        count: 1
      },
      mutations: {
        add (state) {
          state.count++
          store.xxx
        }
      }
    });

    问题在于这个时候 store 还没出生,如何在 add 方法中使用 store 呢? 最终我确定了一个思路:以 Store 的类为核心,通过泛型关联其他四个属性 StateMutationsActionsGetters,如下结构:

    Image text

    然后还是这个问题,如何在 add 方法中使用 store?既然把 Mutations 封装成了类,可以把 store 这个对象绑定到 Mutations 的实例的 this 上面,于是就有了这个约束:

    abstract class ICuer<T> {
      protected readonly store!: T;
    }

    这便是 MutationsActionsGetters 的基类。 但是这样还不够,state 对象也应该关联上,正好一起绑上去,这样同一个 Mutations 的函数互相访问可以省略第一个参数 state

    interface IState<S = unknown> {
      state: S;
    }
    
    abstract class ICuer<T extends IState = IState> {
      protected readonly state!: T["state"];
      protected readonly store!: T;
    }

    于是乎就实现了:

    class Mutations extends ICuer<ExampleStore> {
      /**
       * 加 `1`
      */
      addOne() {
        this.add(1);
      }
    
      /**
       * 加 `v`
      */
      add(v: number) {
        this.state.value += v;
        this.store.xxx
      }
    }

    同理可得 ActionsGetters 当然 Getters 有点区别,他下面的是属性,这并无大碍,构造的时候用 get 属性访问器就行了。 最后就是 Store 类的继承了,Store类 需要知道StateMutationsActionsGetters这四个属性的类型,所以通过泛型来约束:

    class StoreCuer<
      S,
      M extends ICuer = ICuer,
      A extends ICuer = ICuer,
      G extends ICuer = ICuer
    > extends Store<S> {
      constructor(
        state: S,
        options?: {
          mutations?: M;
          actions?: A;
          getters?: G;
          plugins?: StoreOptions<S>["plugins"];
          strict?: StoreOptions<S>["strict"];
        }
      )
    }

    然后把这些类型对应到相应的属性:

    class StoreCuer<
      S,
      M extends ICuer = ICuer,
      A extends ICuer = ICuer,
      G extends ICuer = ICuer
    > extends Store<S> {
      readonly commits!: M;
      readonly dispatchs!: A;
      readonly getters!: G;
    }

    这样就实现了:

    const store = new StoreCuer();
    
    store.getters.xxx //访问 getter
    store.commits.xxx(payload?) //调用 commit
    store.dispatchs.xxx(payload?) //调用 dispatch
    
  3. 优化

    结构和代码逻辑实现了之后就是 vuex 原有的一些如 commitdispatchsubscribesubscribeActionmapStatemapGetters 等函数添加类型约束了。

    • commit 函数的优化

      先重写 interface Commit

      //函数通用类型
      type Method = (...args: unknown[]) => unknown;
      
      //解析函数的参数
      type Params<T> = Parameters<Extract<T, Method>>;
      
      //继承 `vuex` 的 `Commit` 接口并添加约束
      interface CommitEx<M> extends Commit {
        <K extends keyof M>(key: K, payload: Params<M[K]>[0]): unknown;
      }

      StoreCuer 类中重新定义 commit 的类型:

      class StoreCuer<
        S,
        M extends ICuer = ICuer,
        A extends ICuer = ICuer,
        G extends ICuer = ICuer
      > extends Store<S> {
        commit!: CommitEx<M>;
      }

      dispatch 同理可得

    • mapState 函数的优化

      vuexmapState 是全局的,他取的是vue实例化时的入口中的 $store。但是我们既然构造了一个 store 的类,就可以直接在类中实现mapState。 在这里我实现了两种映射(由于混合类型的约束没有达到我想要的精确约束的效果,如果有好的方法各位大佬可以指点一下),一种是参数是 json 格式的

      class StoreCuer<
        S,
        M extends ICuer = ICuer,
        A extends ICuer = ICuer,
        G extends ICuer = ICuer
      > extends Store<S> {
        mapState<V extends Record<keyof V, keyof S>>(keys: V) {
          return mapValueOfJson<S, V>(keys, k => () => this.state[k]);
        }
      }

      另一种是接收字符串数组的参数

      class StoreCuer<
        S,
        M extends ICuer = ICuer,
        A extends ICuer = ICuer,
        G extends ICuer = ICuer
      > extends Store<S> {
        mapStateOfKeys<V extends keyof S>(...keys: V[]) {
          return mapValueOfKeys<S, V>(keys, k => () => this.state[k]);
        }
      }
  4. 最后

    暂时没有实现 module 和 命名空间,因为目前的东西对于我来说是够用的。如果需要统一一个 store 的入口可以这样写:

    // store/test1.store.ts 文件
    //...
    export default test1Store;
    
    // store/test2.store.ts 文件
    //...
    export default test2Store;
    
    // store/index.ts 文件
    import test1Store from "./test1.store.ts";
    import test2Store from "./test2.store.ts";
    
    export default {
      test1Store,
      test2Store
    };
    

    如果要把 index.ts 的对象绑定到全局的 vue 对象上可以这样写:

    import storeCuer from "./store/index.ts";
    
    Vue.prototype.$storeCuer = storeCuer;
    
    //类型约束
    declare module 'vue/types/vue' {
      interface Vue {
        $storeCuer: typeof storeCuer;
      }
    }

用法

  1. class Mutations
    class Mutations extends Cuer.Mutations<ExampleStore> {
    
      test(){
        this.state.xxx //访问 state
        this.store.getters.xxx //访问 getter
        this.xxx //调用当前类的 commit
        this.store.commit("xxx") //调用 commit
        this.store.commits.xxx //调用 commit
      }
    }
  1. class Actions
    class Actions extends Cuer.Actions<ExampleStore> {
    
      test(){
        this.state.xxx //访问 state
        this.store.getters.xxx //访问 getter
        this.xxx //调用当前类的 dispatch
        this.store.commit("xxx", payload?) //调用 commit
        this.store.commits.xxx(payload?) //调用 commit
        this.store.dispatch("xxx", payload?) //调用 dispatch
        this.store.dispatchs.xxx(payload?) //调用 dispatchs
      }
    }
    
  1. class Getters
    class Getters extends Cuer.Actions<ExampleStore> {
      //使用访问器来实现 getter
      get test() {
        this.state.xxx //访问 state
        this.getters.xxx //访问 getter
        this.xxx //访问当前类的 getter
    
        return xxx;
      }
    }
    
  1. class StoreCuer
    // `StoreCuer` 继承自 `vuex` 的 `Store`,支持除 `module` 之外的大部分内容
    
    class ExampleStore extends Cuer.StoreCuer<
      typeof state,
      Mutations,
      Actions,
      Getters
      > {
      constructor() {
        super(state, {
          mutations: new Mutations(),
          actions: new Actions(),
          getters: new Getters()
        });
      }
    }
    
    const store = new ExampleStore();
    
    export default store;
    
    
    store.state.xxx //访问 state
    store.getters.xxx //访问 getter
    store.xxx //访问 Store 的函数
    store.commit("xxx", payload?) //调用 (优化约束,以强化提示)
    store.commits.xxx(payload?) //调用 commit
    store.dispatch("xxx", payload?) //调用 (优化约束,以强化提示)
    store.dispatchs.xxx(payload?) //调用 dispatch
    store.subscribe(fn) // (优化约束,以强化提示)
    store.subscribeAction(fn) // (优化约束,以强化提示)
    store.mapState({...}) // 映射 state
    store.mapStateOfKeys(...) // 映射 state
    store.mapGetters({...}) // 映射 getters
    store.mapGettersOfKeys(...) // 映射 getters
    store.mapActions({...}) // 映射 actions
    store.mapActionsOfKeys(...) // 映射 actions
    store.mapMutations({...}) // 映射 mutations
    store.mapMutationsOfKeys(...) // 映射 mutations