首页 > 其他分享 >vue2升级vue3:vue3真的需要vuex或者Pinia吗?hooks全有了

vue2升级vue3:vue3真的需要vuex或者Pinia吗?hooks全有了

时间:2023-01-25 23:35:23浏览次数:57  
标签:function const hooks variables export vue2 vue3 import store

在写 《vue2升级vue3:TypeScript下vuex-module-decorators/vuex-class to vuex4.x》,建议新项目使用 Pinia,但是我的项目部分组件希望直接打包出去给地方使用。这个时候还是会遇到vue2 是否打包出vuex的 问题。所以,干脆舍弃 vuex/Pinia,直接使用 vue3 原生搞定——hook出现之后,状态管理的问题已经从根本上被消解了!

vue-composition 提供了类似 React Hook 的能力,将 Vue 的抽象层级从「组件级(Component)」降低为「函数级(Function)」。

当掌握了Hook(或者Composition API)之后,感觉万物皆可hook,总是想把数据和操作这堆数据的方法封装在一起!

 

1、方案有以下几种reactive 响应式数据取代store,在各个组件hooks 调用

const store = reactive({state: {})

2、利用rovide和inject,类似react  context,做全局数据管理(不推荐)具体可参看:《vue2升级vue3:provide与inject 使用注意事项

父组件

const person = reactive({name: 'bob', age:32});
provide('person', person);

子组件

const person = inject('person');

有了provide/inject和ref/reactive配合,父子组件/兄弟组件共享状态的问题已经迎刃而解。

通过provide提供了一个reactive响应式对象;然后在子组件通过inject注入该对象。在子组件修改对象的age属性,视图就会响应式更新!同样的,如果child组件也有自己的子组件,调用inject同样有效。具体参看:

 

1、2方法结合:

hooks

export function useUserInfo() {
  const userInfo = reactive({ });
  
  const login = (data) => {...};
  const logout = () => {...};
  const editUserInfo => (data) => {};
  
  return {
   userInfo,
   login,
   logout,
   editUserInfo
  }
}

在根组件调用provide,将userHook函数传入

import {useUserInfo} from '@/hooks/userUserInfo';
provide('user', useUserInfo())

这个 封装好的东西,直接看这个:https://github.com/tbhuabi/vue-di-plugin

但是还是不推荐这个写法!即使 provide/inject 再香,我还是绕道走,总感觉 这玩意和react的 useContext + useReducer 貌似 貌合神离——可以看一下  :https://github.com/tangxiangmin/vue3-hook/tree/master/src/useReducer

 

 

 

1、使用

比如我之前的数据,vuex的

/**
 * 面板查询变量
 */

import { VuexModule, Module, getModule, Mutation } from 'vuex-module-decorators';
import store from '../index';
import { TimeRangeType } from '@/components/time-range';
import { DEFAULT_TIME_RANGE, TimeRange } from '@/components/time-range/utils';
import { FiltersList, FilterType, QueryContextState } from '@/typings';

@Module({ dynamic: true, store, name: 'queryContext' })
export default class QueryContext extends VuexModule implements QueryContextState {
  timeRange: TimeRangeType = DEFAULT_TIME_RANGE;
  timezone = 'Asia/Shanghai';
  variables: FiltersList = {};
  share_uid = '';
  // 缓存的时间 - TimeRangeType 转时间戳
  get getTimeRange(): [number | string, number | string] {
    const date = new TimeRange(this.timeRange);
    const [start, last] = date.value;
    return [start.valueOf(), last.valueOf()];
  }
  @Mutation
  setTimeRange(range: TimeRangeType) {
    this.timeRange = range;
  }
  @Mutation
  setTimezone(zone: string) {
    this.timezone = zone;
  }
  @Mutation
  setShareUid(share_uid: string) {
    this.share_uid = share_uid;
  }
  @Mutation
  setVariation({ name, value }: { name: string; value: FilterType }) {
    // this.variables[name] = value;
    this.variables = { ...this.variables, [name]: value };
  }

  @Mutation
  setVariations(variables: FiltersList) {
    this.variables = variables;
  }
  @Mutation
  clear() {
    this.variables = {};
    this.timeRange = DEFAULT_TIME_RANGE;
  }
}

export const QueryContextModule = getModule(QueryContext);

直接使用响应式数据

import { reactive } from 'vue';
import { FiltersList, FilterType, QueryContextState } from '@/typings';
import { DEFAULT_TIME_RANGE } from '@/components/time-range/utils';
import { TimeRangeType } from '@/components/time-range';
export const QueryContextModule = reactive<QueryContextState>({
  timeRange: DEFAULT_TIME_RANGE,
  timezone: 'Asia/Shanghai',
  variables: {},
  share_uid: '',
});
export function setTimeRange(range: TimeRangeType) {
  QueryContextModule.timeRange = range;
}
export function setTimezone(zone: string) {
  QueryContextModule.timezone = zone;
}
export function setShareUid(share_uid: string) {
  QueryContextModule.share_uid = share_uid;
}
export function setVariation({ name, value }: { name: string; value: FilterType }) {
  QueryContextModule.variables = { ...QueryContextModule.variables, [name]: value };
}
export function setVariations(variables: FiltersList) {
  QueryContextModule.variables = variables;
}
export function clear() {
  QueryContextModule.variables = {};
  QueryContextModule.timeRange = DEFAULT_TIME_RANGE;
}

改为类vuex,可以参看此篇文章: Vue3 还要啥 Vuex,自定义 hooks给你实现数据共享和状态管理 https://juejin.cn/post/7054060160045547550

import { reactive } from 'vue';
import { FiltersList, FilterType } from '@/typings';
import { DEFAULT_TIME_RANGE } from '@/components/time-range/utils';
import { TimeRangeType } from '@/components/time-range';
const store = reactive({
  state: {
    timeRange: DEFAULT_TIME_RANGE,
    timezone: 'Asia/Shanghai',
    variables: {},
    share_uid: '',
  },
});

export function setTimeRange(range: TimeRangeType) {
  store.state.timeRange = range;
}
export function setTimezone(zone: string) {
  store.state.timezone = zone;
}
export function setShareUid(share_uid: string) {
  store.state.share_uid = share_uid;
}
export function setVariation({ name, value }: { name: string; value: FilterType }) {
  store.state.variables = { ...store.state.variables, [name]: value };
}
export function setVariations(variables: FiltersList) {
  store.state.variables = variables;
}
export function clear() {
  store.state.variables = {};
  store.state.timeRange = DEFAULT_TIME_RANGE;
}

export const useQueryContext = () => ({
  store,
  setTimeRange,
  setTimezone,
  setShareUid,
  setVariation,
  setVariations,
  clear,
});

 

这个使用肯定是还太粗糙,项目中使用的代码,等有空的 脱密了在分享一下

 

参考文章:

有了 Vue3 还要啥 Vuex,自定义 hooks给你实现数据共享和状态管理 https://juejin.cn/post/7054060160045547550

 


转载本站文章《vue2升级vue3:vue3真的需要vuex或者Pinia吗?hooks全有了》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/vue3/8881.html

标签:function,const,hooks,variables,export,vue2,vue3,import,store
From: https://www.cnblogs.com/zhoulujun/p/17067433.html

相关文章

  • vue2升级vue3:getCurrentInstance—Composition api/hooks中如何获取$el
    在vue2中,我们进程看到this.$el操作。但是在vue3如何获取组件的当前dom元素呢? 可以利用 getCurrentInstancegetCurrentInstanceVue3.x中的核心方法:getCurrentIns......
  • VUE3/TS/TSX入门手册指北
    VUE3入门手册vue3入门首先查看官方文档:https://cn.vuejs.org/guide/quick-start.html如果有vue2基础,速成课程:https://www.zhoulujun.co/learning-vue3/component.html......
  • Vue2迁移Vue3,如何迁移?
    vue2对比Vue3有很多新特性增加,也有很多功能属于破坏性更新。列举值得关注的新特性第一个肯定是组合式API​​setup​​​以及​​setup语法糖​​模式新增的内置组件......
  • Vue3 setup 如何添加name
    Vue3中name有什么用呢?1.在递归组件的时候需要定义name2.配合keep-aliveincludeexclude可以缓存组件3.在Vue有报错或者调试的时候可以看到组件的nameVue3定义name1.自动......
  • Vue3 proxy 解决跨域
    1.首先我们先了解一下什么是跨域主要是出于浏览器的同源策略限制,它是浏览器最核心也最基本的安全功能。当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不......
  • Vue2.0 双向绑定的原理与缺陷?
    原理Object.defineProperty、getter、setter标准回答Vue响应式指的是:组件的data发生变化,立刻触发试图的更新原理:Vue采用数据劫持结合发布者-订阅者模式的方式来实现数......
  • Vue3.0 实现数据双向绑定的方法
    ue3.0是通过Proxy实现的数据双向绑定,Proxy是ES6中新增的一个特性,实现的过程是在目标对象之前设置了一层“拦截”,外界对该对象的访问,都必须先通过这层拦截,因此提供了一种机......
  • 使用vite创建vue3 遇到 process is not defined
    今天新建项目遇到报错,查资料得出,需要在vite.config.js中添加代码如下import{defineConfig}from'vite'importvuefrom'@vitejs/plugin-vue'import{resolve}f......
  • vue2+SummerNote
    简介:想给加一个富文本编辑器到页面上,选择了summernote。接下来开始把summernote往vue这个框架里塞,死活塞不进去。最后把vue3回退到vue2,世界清净了。大致过程:下载相关包,引......
  • vue3 setup() 参数与使用
    setup(props,context)props:由父组件传入,并且声明过的值,且对应组件props属性上的类型定义context:1.attrs:等同于$attrs,组件外部传入但未声明的值(该值会存在于组件的根元......