functional attribute 在單文件組件 (SFC) <template>
已被移除
{ functional: true } 選項在經過函數建立組件已被移除html
// 使用 <dynamic-heading> 組件,負責提供適當的標題 (即:h1,h2,h3,等等),在 2.x 中,這多是做爲單個文件組件編寫的: // Vue 2 函數式組件示例 export default { functional: true, props: ['level'], render(h, { props, data, children }) { return h(`h${props.level}`, data, children) } } // Vue 2 函數式組件示例使用 <template> <template functional> <component :is="`h${props.level}`" v-bind="attrs" v-on="listeners" /> </template> <script> export default { props: ['level'] } </script>
如今在 Vue 3 中,全部的函數式組件都是用普通函數建立的,換句話說,不須要定義 { functional: true } 組件選項。
他們將接收兩個參數:props 和 context。context 參數是一個對象,包含組件的 attrs,slots,和 emit property。
此外,如今不是在 render 函數中隱式提供 h,而是全局導入 h。
使用前面提到的 <dynamic-heading> 組件的示例,下面是它如今的樣子。vue
// vue3.0 import { h } from 'vue' const DynamicHeading = (props, context) => { return h(`h${props.level}`, context.attrs, context.slots) } DynamicHeading.props = ['level'] export default DynamicHeading // vue3.0單文件寫法 <template> <component v-bind:is="`h${$props.level}`" v-bind="$attrs" /> </template> <script> export default { props: ['level'] } </script>
主要區別在於異步
functional attribute 在 <template> 中移除 listeners 如今做爲 $attrs 的一部分傳遞,能夠將其刪除
如今使用defineAsyncComponent助手方法,用於顯示的定義異步組件
component選項重命名爲loader
Loader函數自己再也不接受resolve和rejuct參數,必須返回一個Promiseasync
// vue2.x // 之前異步組件是經過將組件定義爲返回Promise的函數來建立 const asyncPage = () => import('./NextPage.vue') // 或者以選項方式建立 const asyncPage = { component: () => import('./NextPage.vue'), delay: 200, timeout: 3000, error: ErrorComponent, loading: LoadingComponent } // vue3.x 在vue3.x中,須要使用defineAsyncComponent來定義 import{ defineAsyncComponent } from 'vue' import ErrorComponent from './components/ErrorComponent.vue' import LoadingComponent from './components/LoadingComponent.vue' // 不帶選項的定義方法 const asyncPage = defineAsyncComponent(() => import('./NextPage.vue')) // 帶選項的異步組件 constasyncPageWithOptions = defineAsyncCopmonent({ loader: () => import('./NextPage.vue'), delay: 200, timeout: 3000, errorComponent: ErrorComponent, LoadingComponent: LoadingComponent })
loader函數再也不接收resolve和reject參數,且必須始終返回Promise函數
// vue2.x const oldAsyncComponent = (resolve, reject) => {} // vue3.x const asyncComponent = defineAsyncComponent(() => new Promise((resolve, reject) => {}))
vue3中如今提供了一個emits選項,相似props選項
此選項能夠用於定義組件向其父對象發出的事件code
<!-- vue2.x --> <template> <div> <p>{{ text }}</p> <button v-on:click="$emit('accepted')">OK</button> </div> </template> <script> export default { props: ['text'] } </script> <!-- vue3.x --> <!-- 如今和prop相似,能夠用emits來定義組件發出的事件 --> <!-- 這個選項還接收已給對象,用來向props同樣對傳遞的參數進行驗證 --> <!-- 強烈建議記錄下每一個組件發出的全部emits,由於去掉了.native修飾符,未使用聲明的事件的全部監聽器都將包含在組建的$attr中,默認狀況下,該監聽器將綁定到組件的根節點 --> <template> <div> <p>{{ text }}</p> <button v-on:click="$emit('accepted')">OK</button> </div> </template> <script> export default { props: ['text'], emits: ['accepted'] } </script>