vue 3.x 如何有驚無險地快速入門

前言

本文所分享的是關於 vue 3.x 在用法上的改變,而不是在代碼實現上的不一樣。css

雖然 vue2 到 vue3 的實現大改,但在用法上變化基本不大,比較明顯的一個變化就是添加了 setup(){} 函數了,幾乎全部的配置變成了以函數的方式進行定義。即便是這樣,但小改動仍是不少的。本文主要分享的是 vue 2.x 與 vue 3.x 之間一些常見用法的差別。雖然記錄的很少,但也不算少。本文資料來源:github.com/vuejs/rfcs/…html

固然這裏默認你已經熟練掌握了 vue 2.x 的使用,下面咱們就來看看。vue

新增

composition-api

1.邏輯複用和代碼組織node

這是 vue 3.0 的一個核心變動了。除了改了咱們定義狀態的書寫方式外,也爲咱們提供體驗更棒的邏輯複用和代碼組織,新的方式可讓你把同一個業務邏輯的代碼(狀態,計算屬性,方法等)都放到一塊。這聽起來可能有點不明不白,但若是你寫過比較複雜的組件,你就會發現,這個好。git

2.更好的類型推斷github

更好的支持 TypeScript。api

能夠看這篇文章:github.com/vuejs/rfcs/…數組

或者閱讀這篇(中文):vue-composition-api-rfc.netlify.app/zh/app

teleport 組件

teleport 組件它只是單純的把定義在其內部的內容轉移到目標元素中,在元素結構上不會產生多餘的元素,固然也不會影響到組件樹,它相關於透明的存在。爲何要有這個組件?爲了有更好的代碼組織體驗。好比:有時,組件模板的一部分在邏輯上屬於此組件,但從技術角度來看(如:樣式化需求),最好將模板的這一部分移動到 DOM 中的其餘位置。異步

好比:一些 UI 組件庫的 模態窗、對話框、通知,下拉菜單等須要經過 z-index 來控制層級關係,若是都只是在不一樣的組件或者元素層級中,那麼 z-index 的層級順序就難以保證。可能你會說不少 UI 庫不是都已是這樣的實現了的嗎?至於這個 UI 庫是如何實現的,我猜應該是直接操做 DOM。爲何還要提供這個 teleport 組件呢?多是由於vue 自己的使命使然:儘可能不讓開發者直接操做 DOM,這些事都統一由 VUE 來完成。開發者能夠把更多的時間放在業務的開發上。

<teleport to="#modals">
  <div>A</div>
</teleport>
<teleport to="#modals">
  <div>B</div>
</teleport>

<!-- result-->
<div id="modals">
  <div>A</div>
  <div>B</div>
</div>
複製代碼

更多細節可看:github.com/vuejs/rfcs/…

Suspense

加載異步組件,在異步組件加載完成成並徹底渲染以前 suspense 會先顯示 #fallback 插槽的內容 。

<Suspense>
  <template>
    <Suspended-component />
  </template>
  <template #fallback>
    Loading...
  </template>
</Suspense>
複製代碼

#fallback 實際上是插件 v-solt 的簡寫,而第一個 template 沒有給,則爲默認插槽。

變動

插槽 slot 語法

github.com/vuejs/rfcs/…

適用版本:Version: 2.x,Version: 3.x

將來版本的 vue 中能夠說合二爲一了(slot 和 slot-scope)

<!-- vue 2.x -->
<foo>
  <bar slot="one" slot-scope="one">
    <div slot-scope="bar">
      {{ one }} {{ bar }}
    </div>
  </bar>

  <bar slot="two" slot-scope="two">
    <div slot-scope="bar">
      {{ two }} {{ bar }}
    </div>
  </bar>
</foo>

<!-- vue 3.x -->
<foo>
  <template v-slot:one="one">
    <bar v-slot="bar">
      <div>{{ one }} {{ bar }}</div>
    </bar>
  </template>

  <template v-slot:two="two">
    <bar v-slot="bar">
      <div>{{ two }} {{ bar }}</div>
    </bar>
  </template>
</foo>
複製代碼

我以爲這是好事,合二爲一,不會讓人有一點點的困惑。

簡寫

<TestComponent>
  <template #one="{ name }">Hello {{ name }}</template>
</TestComponent>
複製代碼

指令動態參數

適用版本:Version: 2.x,Version: 3.x

<!-- v-bind with dynamic key -->
<div v-bind:[key]="value"></div>

<!-- v-bind shorthand with dynamic key -->
<div :[key]="value"></div>

<!-- v-on with dynamic event -->
<div v-on:[event]="handler"></div>

<!-- v-on shorthand with dynamic event -->
<div @[event]="handler"></div>

<!-- v-slot with dynamic name -->
<foo> <template v-slot:[name]> Hello </template> </foo>

<!-- v-slot shorthand with dynamic name -->
<!-- pending #3 --> <foo> <template #[name]> Default slot </template> </foo> 複製代碼

簡單地說就是指令名,事件名,插槽名,均可以使用變量來定義了。

Tree-shaking

適用版本:Version: 3.x

在 vue 3 中不會把全部的 api 都打包進來,只會 打包你用到的 api

<!-- vue 2.x -->
import Vue from 'vue'

Vue.nextTick(() => {})

const obj = Vue.observable({})

<!-- vue 3.x -->
import Vue, { nextTick, observable } from 'vue'

Vue.nextTick // undefined

nextTick(() => {})

const obj = observable({})
複製代碼

即咱們在項目中用什麼什麼,就只會打包什麼,不會像 vue 2.x 那樣所有 api 都打包。

.sync 大變樣

適用版本: vue 3.x

<!-- vue 2.x -->
<MyComponent v-bind:title.sync="title" />

<!-- vue 3.x -->
<MyComponent v-model:title="title" />
複製代碼

也就是說,vue 3.0 又去掉了 .sync ,合併到了 v-model 裏,而 v-model 的內部實現也有了小調整

元素

<input v-model="xxx">

<!-- would be shorthand for: -->

<input :model-value="xxx" @update:model-value="newValue => { xxx = newValue }" >

複製代碼

組件

<MyComponent v-model:aaa="xxx"/>

<!-- would be shorthand for: -->

<MyComponent
  :aaa="xxx"
  @update:aaa="newValue => { xxx = newValue }"
/>
複製代碼

不過好像組 alpha 版本的還不支持 v-model:aaa="xxx"

函數組件

適用版本: vue 3.x

<!-- vue 2.x -->
const FunctionalComp = {
  functional: true,
  render(h) {
    return h('div', `Hello! ${props.name}`)
  }
}
    
<!-- vue 3.x -->
import { h } from 'vue'
const FunctionalComp = (props, { slots, attrs, emit }) => {
  return h('div', `Hello! ${props.name}`)
}
複製代碼

再也不須要 functional:true 選項,<template functional> 再也不支付

異步組件也必需經過 api 方法建立

import { defineAsyncComponent } from 'vue'
const AsyncComp = defineAsyncComponent(() => import('./Foo.vue'))
複製代碼

全局 api

適用版本: vue 3.x

在 vue 2.x 中

import Vue from 'vue'
import App from './App.vue'

Vue.config.ignoredElements = [/^app-/]
Vue.use(/* ... */)
Vue.mixin(/* ... */)
Vue.component(/* ... */)
Vue.directive(/* ... */)

Vue.prototype.customProperty = () => {}

new Vue({
  render: h => h(App)
}).$mount('#app')
複製代碼

在 vue 3.x 中

import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

app.config.isCustomElement = tag => tag.startsWith('app-')
app.use(/* ... */)
app.mixin(/* ... */)
app.component(/* ... */)
app.directive(/* ... */)

app.config.globalProperties.customProperty = () => {}

app.mount(App, '#app')
複製代碼

能夠看到,建立實例的方式也改變了。一些全局的 api 方法也不在全局上了,而是放到了實例上。

更多的改變能夠看這裏:github.com/vuejs/rfcs/…

v-model

適用版本:Version 3.x

1.原來的方式保留

<input v-model="foo">
複製代碼

2.可綁定多個 v-model

<InviteeForm v-model:name="inviteeName" v-model:email="inviteeEmail" />
複製代碼

其實上面這種方式就至關於以前的 .sync 。

3.額外處理

<Comp v-model:foo.trim="text" v-model:bar.number="number" />
複製代碼

咱們能夠給這個屬性添加額外的處理

指令的鉤子函數

適用版本:Version 3.x

在 vue 3.x 中 指令的鉤子函數仿照了組件中的鉤子函數命名規則

vue 2.x 時

const MyDirective = {
  bind(el, binding, vnode, prevVnode) {},
  inserted() {},
  update() {},
  componentUpdated() {},
  unbind() {}
}
複製代碼

vue 3.0 中

const MyDirective = {
  beforeMount(el, binding, vnode, prevVnode) {},
  mounted() {},
  beforeUpdate() {},
  updated() {},
  beforeUnmount() {}, // new
  unmounted() {}
}
複製代碼

transition

適用版本:Version 3.x

<transition> 做爲組件的根元素時,外部切換不會觸發過渡效果

vue 2.x

<!-- modal component -->
<template>
  <transition>
    <div class="modal"><slot/></div>
  </transition>
</template>

<!-- usage -->
<modal v-if="showModal">hello</modal>
複製代碼

vue 3.x

<!-- modal component -->
<template>
  <transition>
    <div v-if="show" class="modal"><slot/></div>
  </transition>
</template>

<!-- usage -->
<modal :show="showModal">hello</modal>
複製代碼

也就是說咱們只能在 <transition> 內使用切換。

transition-class

重命名兩個過渡類

v-enter 重命名成v-enter-fromv-leave重命名成 v-enter-from

.v-enter-from, .v-leave-to {
  opacity: 0;
}
.v-leave-from, .v-enter-to {
  opacity: 1
}
複製代碼

Router

適合版本:Version: Vue (2.x / 3.x) Vue Router (3.x / 4.x)

1.router-link 添加 scoped-slot API 和 custom 屬性,並移除了 tag 屬性和 event 屬性。

添加 scoped-slot 有什麼用呢?之前只能經過 active-class 來改變元素樣式的,如今有了 scoped-slot 以後,咱們就更加靈活了,能夠根據 scoped-slot 回傳的狀態自定義,不論是樣式仍是類。

<router-link to="/" custom v-slot="{ href, navigate, isActive }">
  <li :class="{ 'active': isActive }">
    <a :href="href" @click="navigate">
      <Icon>home</Icon><span class="xs-hidden">Home</span>
    </a>
  </li>
</router-link>
複製代碼

也就是說,新版本的 Router 就更加的純粹,只提供給咱們一些參數,讓咱們本身利用這些參數來實現不一樣的場景。

2.meta 合併

{
  path: '/parent',
  meta: { requiresAuth: true, isChild: false },
  children: [
    { path: 'child', meta: { isChild: true }}
  ]
}

複製代碼

當訪問 /parent/child 時,子路由中的 meta 以下:

{ requiresAuth: true, isChild: true }
複製代碼

合併策略與 Object.assign 相似

樣式 scoped

適用版本:Version: 2.x, 3.x

舊版本寫法

/* 深度選擇器 */
/*方式一:*/
>>> .foo{ }
/*方式二:*/
/deep/ .foo{ }
/*方式三*/
::v-deep .foo{ }
複製代碼

新版本寫法

/* 深度選擇器 */
::v-deep(.foo) {}
複製代碼

除了上面的深度選擇器外,還有下面的兩個,寫法也差很少。

/* slot content 起做用 */
::v-slotted(.foo) {}

/* 全局 */
::v-global(.foo) {}
複製代碼

屬性值修正

適用版本:Version: 3.x

vue 自己會對元素的屬性做相應的處理。在舊版本的 vue 中處理以下:

表達式 正常 最終處理成
:attr="null" / draggable="false"
:attr="undefined" / /
:attr="true" foo="true" draggable="true"
:attr="false" / draggable="false"
:attr="0" foo="0" draggable="true"
attr="" foo="" draggable="true"
attr="foo" foo="foo" draggable="true"
attr foo="" draggable="true"

新版本處理方式:

表達式 正常 最終處理成
:attr="null" / /
:attr="undefined" / /
:attr="true" foo="true" draggable="true"
:attr="false" foo="false" draggable="false"
:attr="0" foo="0" draggable="0"
attr="" foo="" draggable=""
attr="foo" foo="foo" draggable="foo"
attr foo="" draggable=""

在新版本中基本保持了原樣,也就是咱們給元素添加什麼屬性值,最好 vue 處理完後仍是什麼屬性值。

異步組件

import { defineAsyncComponent } from "vue"

// simple usage
const AsyncFoo = defineAsyncComponent(() => import("./Foo.vue"))
複製代碼

寫法上與以前有些不同。

動態路由

適用版本 Router 4

添加了幾個方法

  1. router.addRoute(route: RouteRecord) 動態添加路由
  2. router.removeRoute(name: string | symbol),動態刪除路由
  3. router.hasRoute(name: string | symbol): boolean ,判斷路由是否存在
  4. router.getRoutes(): RouteRecord[] 獲取路由列表
router.addRoute({
  path: '/new-route',
  name: 'NewRoute',
  component: NewRoute
})

// add to the children of an existing route
router.addRoute('ParentRoute', {
  path: 'new-route',
  name: 'NewRoute',
  component: NewRoute
})

router.removeRoute('NewRoute')

// normalized version of the records added
const routeRecords = router.getRoutes()
複製代碼

詳情可見:github.com/vuejs/rfcs/…

emits-option

const Foo = defineComponent({
  emits: {
    submit: (payload: { email: string; password: string }) => {
      // perform runtime validation
    }
  },

  methods: {
    onSubmit() {
      this.$emit('submit', {
        email: 'foo@bar.com',
        password: 123 // Type error!
      })

      this.$emit('non-declared-event') // Type error!
    }
  }
})

複製代碼

如今的 $emit() 方法在用法上沒變,但須要額外多定義 emits 對象,但要注意的是如今 alpha 版本還不支持 TypeScript

組件根元素數量

vue 3 後組件再也不限制 template 中根元素的個數(舊的版本以前是隻能有一個根元素)。

vue 3.x 中費棄

  • filters
  • keycode
  • inline-template
  • data-object
  • on,off 和 $once

閱讀完本文我相信你大概對 vue 3 有了一個基本的認識。雖然本文會不讓你瞬間成爲 vue 3.x 的駕馭者,但怎麼說也讓你含蓄地體驗了一把 vue 3.x 的新特性。特別是 composition API 即便本文沒有詳細寫出來,但經過補充的連接,你也能閱讀到它的全部。我以爲 composition API 真的很棒。

相關文章
相關標籤/搜索