學習 Vue3.0 (3)

Fragment

  • 在 Vue 2 中,組件必須有一個根標簽
  • 在 Vue 3 中,組件可以沒有根標簽,內部會將多個標簽包含在一個 Fragment 虛擬元素中
  • 減少標簽嵌套層級、減少內存占用

Teleport

  • 能夠將組件內部的某些內容渲染到外部的某個元素上
<teleport to="targetDom">
  <div v-if="isShow">
    <p>這是內部的內容</p>
  </div>
</teleport>

Suspense

  • 等待異步組件時,渲染一些后備內容,獲得更好的用戶體驗
<!-- 
  // 父組件 
  // 使用suspense包裹,配置好default與fallback 
-->
<div>
  <Suspense>
    <template>
      <Child></Child>
    </template>
    <template v-slot:fallback>
      <div>loading...</div>
    </template>
  </Suspense>
</div>

<!-- 第一步 引入異步組件 -->
<script>
  import { defineComponent } from 'vue';
  const Child = defineComponent(() => import('../components/Child.vue'));

  export default {
    components: {
      Child
    }
  };
</script>

// 子組件
// 方式一
setup(){
  let sum = ref(0)
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({sum})
    }, 1000)
  })
}
// 方式二
async setup(){
  let sum = ref(0)
  let p = new Promise(resolve => {
    setTimeout(() => {
      resolve({sum})
    }, 1000)
  })
  return await p
}

Vue 3 中其他改變

1. 將全局的 API 調整到應用實例 app 上

2.x 全局 API(Vue) 3.x 實例 API(app)
Vue.config.xxx app.config.xxx
Vue.config.productionTip 移除
Vue.component app.component
Vue.directive app.directive
Vue.mixin app.mixin
Vue.use app.use
Vue.prototype app.config.globalProperties

2. data 選項應始終聲明為一個函數

3. 移除 keyCode 作為 v-on 的修飾符,同時也不再支持 config.keyCodes

4. 移除 v-on.native 修飾符

//父組件
<child
  :click="handleClick"   // 未在子組件中定義認為原生事件
  :close="handleClose"   // 在子組件中定義過的自定義事件
></child>

// 子組件
<script>
  export default{
    emits:['close']
  }
</script>

5. 移除過濾器(filter)

在 3.x 中,過濾器已移除,且不再支持。取而代之的是,我們建議用方法調用或計算屬性來替換它們。

// 全局過濾器
const app = createApp(App)

app.config.globalProperties.$filters = {
  formateDate(value) {
    return value.toLocaleDateString()
  }
}

//  組件中使用

<p>{{ $filters.formateDate(new Date()) }}</p>

6. 移除$listeners

在 Vue 3 的虛擬 DOM 中,事件監(jiān)聽器現在只是以 on 為前綴的 attribute,這樣它就成為了 attrs 對象的一部分,因此listeners 被移除了,

// 父組件
<child msg="hello word" @close="handleClose"></child>

// 子組件
<template>
  <div v-bind="$attrs">
    <h1>text</h1>
  </div>
  <div>hello</div>
</template>
<script>
  export default {
    ......
    setup(props: any, { emit, slots, attrs }: any) {
      console.log('props', props);
      console.log('emit', emit);
      console.log('slots', slots);
      console.log('attrs', attrs);  // Proxy {msg: 'Hello World', __vInternal: 1, onClose: ?}
    }
  };
</script>
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容