vue2升級到vue3的一些注意事項


向數組中push,不會出發watch更新

  setup() {
    let state = reactive({
      list: []
    })
    watch(
      () => state.list,
      (val) => {
        console.log(val)
      }
    )

    state.list.push(1) // 不會觸發watch,不知道vue為什么這么做

    state.list = [1] // 重新賦值,會觸發watch
  }

template 可以不再需要頂層節點

<template>
<Header/>
<Footer/>
</template>

teleport把節點掛載到指定id下

<teleport to="#endofbody">
    <div class="modal">
     hello world
    </div>
</teleport>

Suspense組件,展示加載狀態

<Suspense>
  <template >
      <!-- 異步組件 -->
    <Suspended-component />
  </template>
  <template #fallback>
      <!-- 異步組件加載完畢前展示的內容 -->
    Loading...
  </template>
</Suspense>

升級指南

鍵盤綁定keycode無效,綁定別名有效


<!-- 無效 -->
<input v-on:keyup.13="submit" />

<!-- 有效 -->
<input v-on:keyup.enter="submit" />

移除on off 和 $once方法,使用mitt代替

filters被移除,使用methods或者computed代替

全局api調用方式改變

import Vue from 'vue'

Vue.mixin()

Vue.use()


import { createApp } from 'vue'

const app = createApp({})

app.mixin()

app.use()

setup 中可以實現之前的所有邏輯


setup() {
    onMounted(() => {
      console.log(333)
    })
}

全局屬性掛載方法改變

// old
Vue.prototype.http = functuin() {}


// new
app.config.globalProperties.http = function(){}

this.http

render 方法修改

// old
render(h) {
    return h('div')
}


// new
import { h} from 'vue'

render() {
    return h('div')
}

data必須是一個函數

data() {
    return {}
}

支持定義異步組件


import { defineAsyncComponent } from 'vue'

// one
const asyncPageWithOptions = defineAsyncComponent({
  loader: () => import('./NextPage.vue'),
  delay: 200,
  timeout: 3000,
  error: ErrorComponent,
  loading: LoadingComponent
})

// two
const asyncComponent = defineAsyncComponent(
  () =>
    new Promise((resolve, reject) => {
      /* ... */
    })
)

使用非html元素的標簽

app.config.isCustomElement = tag => tag === 'plastic-button'

在普通元素上使用is被v-is代替,component組件上仍然可以使用is

<button v-is="plastic-button">Click Me!</button>

<component is="plastic-button"></component>

this.\(scopedSlots將會被移除,統一替代成this.\)slots

// old
h(LayoutComponent, [
  h('div', { slot: 'header' }, this.header),
  h('div', { slot: 'content' }, this.content)
])


this.$scopedSlots.header


// new
h(LayoutComponent, {}, {
  header: () => h('div', this.header),
  content: () => h('div', this.content)
})
this.$slots.header

指令生命周期修改


Vue.directive('highlight', {
  beforeMount(el, binding, vnode) { // 對應bind
    el.style.background = binding.value
  },
  mounted() {}, // 對應inserted
  beforeUpdate() {}, // 新增
  updated() {}, // 對應update
  beforeUnmount() {}, // 新增
  unmounted() {} // 對應unbind
})

watch方法,不再支持通過.進行監聽。包括 this.$watch 監聽

watch: {
    // watch vm.e.f's value: {g: 5}
    'e.f': function (val, oldVal) { /* ... */ }
  }

vue-router 4的新功能

// 守衛不再需要next,並且支持async
router.beforeEach(async (to, from) => {
  // canUserAccess() returns `true` or `false`
  return await canUserAccess(to)
})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM