Vue兩種元件型別:遞迴元件和動態元件的用法
阿新 • • 發佈:2020-08-07
一遞迴元件
遞迴元件的特性就是可以在自己的template模板中呼叫自己本身。值得注意的它必須設定name屬性。
// 遞迴元件 recursive.vue <template> <div> <p>遞迴元件</p> <Recursion :count="count + 1" v-if="count < 3"></Recursion> </div> </template> <script> export default { name: "Recursion",//必須設定name屬性 props: { count: { type: Number,default: 1 } } } </script>
這個例子中父頁面使用該遞迴元件會呼叫三次recursive元件,值得注意的是遞迴元件必須設定遞迴次數限制數量
否則會丟擲錯誤,該例子中通過count來限制遞迴次數。
二 動態元件
如果將一個Vue元件命名為Component會報錯,因為Vue提供來特殊的元素<component>來動態掛載不同元件。
並使用is特性來選擇要掛載的元件。
// parentComponent.vue <template> <div> <h1>父元件</h1> <component :is="currentView"></component> <button @click = "changeToViewB">切換到B檢視</button> </div> </template> <script> import ComponentA from '@/components/ComponentA' import ComponentB from '@/components/ComponentB' export default { components: { ComponentA,ComponentB },data() { return { currentView: ComponentA // 預設顯示元件 A } },methods: { changeToViewB () { this.currentView = ComponentB // 切換到元件 B } } } </script>
通過改變currentView的值就可以動態切換顯示的元件,與之類似的是vue-router的實現原理,前端路由到不同的頁面實際上就是載入不同的元件。
補充知識:Vue route部分簡單高階用法
一、改變頁面title的值
在開發時常常需要在切換到不同頁面時改變瀏覽器的title值,那麼我們就可以在定義路由的時候通過配置 meta 屬性
來改變title值。
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) import UserInfo from ".././userInfo.vue"; import ChangeCommunity from ".././ChangeCommunity.vue"; var vueRouter= new Router({ routes: [ { path: '/',name: 'UserInfo',component: UserInfo,meta: { title: '我的資訊' } },{ path: '/ChangeCommunity',name: 'ChangeCommunity',component: ChangeCommunity,meta: { title: '我的社群' } },] }) vueRouter.beforeEach((to,from,next) => { /* 路由發生變化修改頁面title */ if (to.meta.title) { document.title = to.meta.title; } next(); }) export default vueRouter
當從我的資訊頁面跳轉到我的社群頁面時,對應的title值也會由“我的資訊”變成“我的社群”。
二、路由懶載入
當專案頁面比較多時,初始化時候載入所有頁面路由,效能十分差,這時候就可用懶載入,要渲染那個頁面就載入那個頁面。
例如:
{ path: '/ChangeCommunity',resolve },
還可以
{ path: '/ChangeCommunity',component: resolve=>require(['ChangeCommunity'],resolve) },
兩種寫法都可以。
三 、滾動行為
使用前端路由,當切換到新路由時,想要頁面滾到頂部,或者是保持原先的滾動位置,就像重新載入頁面那樣。
vue-router 能做到,而且更好,它讓你可以自定義路由切換時頁面如何滾動。
注意:這個功能只在支援 history.pushState 的瀏覽器中可用。
例如:
const router = new VueRouter({ routes: [...],scrollBehavior (to,savedPosition) { if (savedPosition) { return savedPosition//滾動到指定位置 } else { return { x: 0,y: 0 } } } }) “滾動到錨點”的行為: scrollBehavior (to,savedPosition) { if (to.hash) { return { selector: to.hash } } } 非同步滾動 scrollBehavior (to,savedPosition) { return new Promise((resolve,reject) => { setTimeout(() => { resolve({ x: 0,y: 0 }) },500) }) }
以上這篇Vue兩種元件型別:遞迴元件和動態元件的用法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。