Vue-router
路由過渡動畫
利用<transition>
標籤可以給路由加上過渡動畫,這裏只是利用了簡單的動畫效果。
在src/App.vue
文件中加入<transition>
標籤,包裹在<router-view>
的外部。
此時還需要給一個name屬性,這裏name屬性設置爲test
。
<template>
<div id="app">
<img src="./assets/logo.png">
<div>
<router-link to="/">跳轉到首頁面</router-link> |
<router-link to="/demot">跳轉到demot頁面</router-link>|
<router-link :to="{name:'Demot1',params:{username:'Luck',age:80}}">跳轉到demot1頁面</router-link>|
<router-link :to="{name:'Demot2',params:{username:'Jack',age:56}}">跳轉到demot2頁面</router-link>|
<router-link to="/params/120/武漢櫻花">傳遞參數params頁面</router-link>
<br>
<p>
<router-link to="/demo">demo頁面</router-link>|
<router-link to="/demo2">返回demo頁面</router-link>|
<router-link to="/params/525/杭州西湖">攜帶參數返回params頁面</router-link>|
<router-link to="/lucy">lucy頁面</router-link>|
<router-link to="/trans">trans頁面</router-link>
</p>
</div>
<transition name="test" mode="out-in">
<router-view></router-view>
</transition>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.test-enter{
opacity: 0;
}
.test-enter-active{
transition: opacity .5s;
}
.test-leave{
opacity: 1;
}
.test-leave-active{
opacity: 0;
transition:opacity .5s;
}
</style>
- test-enter:進入過渡的開始狀態,元素被插入時生效,只應用一幀後立刻刪除。
- test-enter-active:進入過渡的結束狀態,元素被插入時就生效,在過渡過程完成後移除。
- test-leave:離開過渡的開始狀態,元素被刪除時觸發,只應用一幀後立刻刪除。
- test-leave-active:離開過渡的結束狀態,元素被刪除時生效,離開過渡完成後被刪除。
注意:test-enter-active和test-leave-active在整個進入或離開過程中都有效
過渡模式mode:
in-out
:新元素先進入過渡,完成之後當前元素過渡離開。
out-in
:當前元素先進行過渡離開,離開完成後新元素過渡進入。
路由配置mode和404頁面的處理
1.在路由配置文件src/router/index.js
中,若增加mode
屬性,那麼瀏覽器中的url地址將會發生變化。
mode的兩種模式:
-
hash
值:這個是默認的mode值,這時瀏覽器中的url地址將會多了一個#
符號。例如:http://localhost:8080/#/
-
history
值:當你使用 history 模式時,URL 就像正常的 url,例如:http://localhost:8080/
當路由配置中mode屬性的值是hash
時:(注意觀察瀏覽器地址欄 的不同)
export default new Router({
mode:'hash',
routes: [
{
path:'/',
name:'HelloWorld',
component:HelloWorld
}
]
})
運行結果:
當路由配置中mode屬性的值是histroy
時:(注意觀察瀏覽器地址欄 的不同)
export default new Router({
mode:'history',
routes: [
{
path:'/',
name:'HelloWorld',
component:HelloWorld
}
]
})
運行結果:
404頁面的處理
2.當用戶在瀏覽器中輸入錯誤的網址時,網頁並不會顯示“網頁不存在”,也不報錯,這使得用戶的體驗感不是很好。
這時我們就可以自己創建一個錯誤提示頁面Error
- 在src/components目錄下新建
Error.vue
文件,並在網頁中輸出msg:“404錯誤,頁面不存在”。
<template>
<div>
<h3>{{msg}}</h3>
<p>網頁不存在</p>
</div>
</template>
<script>
export default{
data(){
return{
msg:'404錯誤,頁面不存在'
}
}
}
</script>
<style>
</style>
- 在
src/router/index.js
文件中引入Error文件
import Error from '@/components/error'
- 在
src/router/index.js
文件中進行路由配置,此時path
參數配置爲*
{
path:'*',
component:Error
}
當瀏覽器的地址欄裏面輸入不存在的網頁時,會出現以下頁面: