用上Vue3,你真的变了吗?

12,204 阅读5分钟

前言

Vue3已经发布很长一段时间了,虽然早就用上了框架,但是很多人依旧保持着Vue2的思维习惯,导致大家在实际开发中并没有感觉到提升,属实是新瓶装旧酒。我们应该意识到这并不仅仅是一个数字大版本的迭代,而是一次全新的开发体验。

让我们一起看看在使用Vue3开发时,应该在哪些地方做出改变?

正文

使用<script setup>

如果是从Vue2转到Vue3,我们很熟悉的一种写法是选项式API写法。

<template>
  <div :class="$style.container">
    <div class="title">{{ title }}</div>
    <CompA />
  </div>
</template>
<script>
import CompA from './CompA.vue'
export default {
  components: { CompA },
  setup (props, context) {
    return {}
  },
  methods: {
    doSomething () {
      // do something
    },
  },
}
</script>
<style lang="scss" module>
</style>

通过export default导出一个对象,内部的datamethodswatch都可以使用,this依然可以保留,并指向vuesetup中如果想用propsemit等,通过参数传递。在setup中可以直接使用新写法,组件通过components进行引入。可以极大的还原Vue2的用法,如果团队的组件库是使用Vue2写的,可以用很小的成本就改造完成。

为了更好的类型推导,vue还提供了defineComponent方法。

export default defineComponent({
  components: { CompA },
  setup (props, context) {
     // do something
  },
})

但其实官方并不推荐这种写法,这种写法仅仅是为了兼容旧代码,这也是你感觉Vue3没有提升的很大一方面因素。就像是iPhone更新,当外观有变化时你才会觉得是大更新,系统升级个IOS18,你觉得卵用没用。所以更好的方式应该是<script setup>标签对的写法。

<script setup lang="ts">
import { onMounted, ref } from 'vue'
const title = ref<string>('')
onMounted(() => {
  title.value = 'Demo'
})
</script>

<template>
  <div :class="$style.container">{{ title }}</div>
</template>

<style lang="scss" module>
</style>

你会发现有很多核心的变化,首先不再需要export导出了,标签对内直接就是一个setup环境。ref可以直接写,也没有了methods,你写一个就是一个方法,直接就可以绑定。为什么呢?官方不是说所有的值都需要return出去吗?放心,@vue/compiler-sfc帮你解决了这些烦恼。

其次这种写法是去this化的,比如以往我们调用router都是this.$router这么使用,而现在你需要引入useRouter,可以更好的分辨来源。对ts也更友好。

import { useRouter } from 'vue-router'
const router = useRouter()

组件使用也更方便,直接引入即可。

<script setup lang="ts">
import CompA from './CompA.vue'
</script>
<template>
  <div :class="$style.container">
    <CompA />
  </div>
</template>

同名简写

以往我们绑定一个值需要这样:

<template>
  <div :id="id">
    <Comp :title="title" />
  </div>
</template>
<script>
export default {
  data () {
    return {
      id: 'container',
      title: '标题',
    }
  },
}
</script>

而现在变得极其简单,尤其是Vue升级到v3.4.x以上之后,因为它增加了同名简写。

<script setup lang="ts">
const id = ref('container')
const title = ref('标题')
</script>
<template>
  <div :id>
    <CompA :title />
  </div>
</template>

怎么样,有没有觉得非常优雅,不过比较可惜的是这个写法esLint目前还不支持,会报异常,需要在.eslintrc中忽略一下。

"rules": {
   "vue/valid-v-bind": "off"
}

拒绝mixins

我们之前Vue2的模版中有很多的mixins,而且不乏有全局引入的mixins,在迁移模板时,也需要一起处理,我看到官方也有案例,有mixins的,还有extends的。

const mixin = { 
  created() { console.log(1) } 
}
createApp({ 
  created() { console.log(2) }, 
  mixins: [mixin] 
})

但是均都对组合式API不友好,因为mixin内部有不少调用this内部环境的地方,很难在<script setup>中使用,而且mixins最大的问题就是,你无法溯源,别人在某个犄角旮旯引入一个全局mixins,你根本找不到,而且也对类型推导极其不友好。所以建议使用组合式函数代替。比如我们之前有一个NavBarmixins,里面处理了很多逻辑,就可以用组合式函数进行封装。

import { onMounted, ref } from 'vue'

const commonProps = {}
const useNavbar = () => {
  const navbarProps = ref<any>({})
  const setNavbar = (newProps?: any) => {
    navbarProps.value = {
      ...navbarProps.value,
      ...newProps || {},
      ...commonProps,
    }
    if (navbarProps.value.title && typeof document !== 'undefined') {
      document.title = navbarProps.value.title
    }
  }
  onMounted(() => {
    //  init
  })
  return {
    navbarProps,
    setNavbar,
  }
}
export default useNavbar

在使用时引用进来即可,而且只要你调用了useNavbar,内部的onMounted也会执行,非常方便。

import useNavbar from './useNavbar'
const { navbarProps, setNavbar} = useNavbar()

减少全局变量

之前在Vue2时,我们经常会将一些常用属性挂载在Vue.prototype原型上,方便内部用this.xxx使用。比如我们会把Request挂载上去,Vue.prototype.$request = Request。我们发送请求时直接this.$request即可,很方便。其实很多Vue2的依赖库都是这么写的,比如vue-router,就是在install中将$router写为了全局变量,在我们使用Vue.use(Router)后,方便我们使用。

vue-router源码 而在Vue3中也有替代方案,app.config.globalProperties.$request = Request。 但是在使用时就比较麻烦了,因为没有this环境,需要从实例上取。

import { getCurrentInstance } from 'vue'
const $this = getCurrentInstance()?.appContext.config.globalProperties
$this?.$request.post('/url', {})

很深的API,既然这么深,我想我封装一下吧。

// vueThis.ts
import { getCurrentInstance } from 'vue'
export default getCurrentInstance()?.appContext.config.globalProperties

// 使用时
import vueThis from './vueThis'
vueThis.$request.post('/url',{})

但是你说气人不,getCurrentInstance还要识别调用的时机,你直接赋值,相当于引入时就运行了,这个时候还没实例,你还得闭包包一下,调用也不好看。

// vueThis.ts
export default () => {
  return getCurrentInstance()?.appContext.config.globalProperties
}

// 使用时
import vueThis from './vueThis'
const $this = vueThis()
$this.$request.post('/url',{})

而且不光如此,你挂载全局变量,想要有类型推导,你还要在vue-runtime-core.d.ts把类型告诉人家,才好用。特别不优雅。

import request from '@host/request'
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $request: typeof request
  }
}

所以依旧建议使用组合式函数进行封装,清晰又明了。

// useRequest.ts
export default () => {
  const get = async (uri: string, params: any = {}) => {
    return await Request.get(uri, params)
  }
  const post = async (uri: string, params: any = {}) => {
    return await Request.post(uri, params)
  }
  return {
    get,
    post,
  }
}

// 使用时
import useRequest from './useRequest'
const { post } = useRequest()
post('/url',{})

一个use只办一件事

Vue2始终是以页面为单位进行思考的,即一个vue只办一件事,至于提供的mixin也好,props也好,emit也好,都是为了服务这个vue本身的,所有也是为什么简单页面vue最好用。

但是伴随着一个vue的功能越来越多,代码也就越来越复杂,就变成了左图Options API的样子,再加上全局属性的乱加,mixins的乱用,组件的乱引,整体也变得越来越冗余,最终变成了大家吐槽的对象。

Vue3推出的组合式函数的概念,借鉴了React Hooks的写法,将原本一个vue一件事抽象成一个vue几件事,再用函数进行打包。最终就是Composition API的样子。所以我们开发时就应该顺应Vue3的思维:一个use只办一件事image.png 举几个案例:

  • useRequest --> 这个use只管请求,配置也好,初始化也好,都在内。
  • useNavbar --> 这个函数只管navBar
  • useDevice --> 这个函数只管设备相关的内容
  • useLoad --> 这个函数只管加载

抛弃index命名

Vue2常规的项目路径是这样的:

- pages
    - home
        - img
        - components
            - CompA.vue
            - CompB.vue
        - index.vue
    - rule
        - index.vue

已经很整洁了,但是我建议改成这样:

- pages
    - home
        - img
        - components
            - CompA.vue
            - CompB.vue
        - Home.vue
    - rule
        - Rule.vue

为什么呢?因为Vue3有个特性,在<script setup>模式下,无法指定组件名称,也就意味着路由名称也无法指定,所以文件名就是组件名,就是路由名称,所以建议全部使用语义化文件名。

如果用index,他的路由名称就会是index,非常不友好。比如你在区分哪些需要使用KeepAlive时,你就无法识别。

<router-view v-slot="{ Component }">
  <!-- 如果使用的是index.vue,在这里无法通过include判断 -->
  <keep-alive :include="['Home']">
    <component :is="Component" />
  </keep-alive>
</router-view>

总结

这是我最近迁移模板总结的一些经验,怎么样,有让大家对Vue3有一些改观吗?

大家还有没有其他一些老习惯没改的,欢迎一起讨论。