vue-router 其他

項目前導 學習筆記

一、匹配 404 錯誤


        在路由規則中,* 代表的是任意字符。所以只要在路由的最後添加一個 * 路由,那麼以後沒有匹配到的url都會被導入到這個視圖中。

	<script>
	...
		var UserProfile = {template:"<h1>個人中心:{{$route.params.userid}}</h1>"};
		var NotFound = {template: "<h1>您找的頁面已經到火星啦!</h1>"}
		var routes = [
		    {path: "/user/:userid",component: UserProfile},
		    
		    // 上面的都匹配完了都找不到, 再返回 404, 所以放在最後
		    {path: "*",component: NotFound},
		]
	...
	</script>



二、嵌套路由


        有時候在路由中,主要的部分是相同的,但是下面可能是不同的。比如訪問用戶的個人中心是 /user/111/profile/,查看用戶發的貼子是 /user/111/posts/ 等。這時候就需要使用到嵌套路由。

在這裏插入圖片描述

	<script>
	    var index = Vue.extend({ template: "<h1>首頁</h1>" })
	    var user = Vue.extend({
	        template:
	        `
	          <div>
	            <h1>個人中心</h1>
	            <ul class="nav nav-tabs">
	              <li role="presentation" class="active">
	                  <router-link to="/user/123/message">信息</router-link>
	              </li>
	              <li role="presentation">
	                  <router-link to="/user/123/setting">設置</router-link>
	              </li>
	            </ul>
	            <div class="container">
	                <!--  注意這裏也要有路由出口  -->
	                <router-view></router-view>
	            </div>
	          </div>
	        `
	    })
	    var message = Vue.extend({ template: "<h1>信息</h1>" })
	    var setting = Vue.extend({ template: "<h1>設置</h1>" })
	
	    var router = new VueRouter({
	        routes: [
	            { path: "/", component: index },
	            {
	                path: "/user/:userid",
	                component: user,
	                children: [
	                    // 這裏的路徑都是 /user:userid 下的, 所以不用寫全
	                    { path: "message", component: message },
	                    { path: "setting", component: setting },
	                    // 默認顯示頁面
	                    { path: "", component: message },
	                ]
	            },
	        ]
	    })
	
	    new Vue({
	        el: "#app",
	        router: router
	    });
	</script>



三、編程式導航


        之前使用 <router-link> 可以在用戶點擊的情況下進行頁面更新。但有時候我們想要在 js 中手動的修改頁面的跳轉,這時候就需要使用編程式導航了。

        想要導航到不同的 URL,則使用 $router.push 方法。這個方法會向 history 棧添加一個新的記錄(就是能實現頁面前進後退功能),所以,當用戶點擊瀏覽器後退按鈕時,則回到之前的 URL

        當你點擊 <router-link> 時,這個方法會在內部調用,所以說,點擊 <router-link :to="..."> 等同於調用 router.push(...)

    <div id="app">
        <button @click="goprev">上一步</button>
        <button @click="gotoLis">列表</button>
        <button @click="gotoProfile">個人中心</button>
        <button @click="login">登錄</button>
        <button @click="gonext">下一步</button>
        <router-view></router-view>
    </div>


	<script>
	    var lis = Vue.extend({ template: "<h1>列表</h1>" })
	    var profile = Vue.extend({ template: "<h1>個人中心{{$route.params.userid}}</h1>" })
	    var login = Vue.extend({ template: "<h1>登錄</h1>" })
	    var router = new VueRouter({
	        routes: [
	            {path: "/lis", component: lis},
	            {path: "/profile/:userid", component: profile, name: "myprofile"},
	            {path: "/login", component: login},
	        ]
	    });
	
	    new Vue({
	        el: "#app",
	        router: router,
	        methods: {
	            gotoLis(){
	                // 字符串 地址格式:/lis
	                this.$router.push("/lis")
	            },
	            gotoProfile(){
	                // 對象 地址格式:/profile/123
	                this.$router.push({ name: "myprofile", params:{userid:"123"} })
	            },
	            login(){
	                // 地址格式:/login?wd=SignIn
	                this.$router.push({ path: "login", query:{wd:"SignIn"} })
	            },
	            goprev(){
	            	// 上一步
	                this.$router.go(1)
	            },
	            gonext(){
	            	// 下一步
	                this.$router.go(-1)
	            }
	        }
	    });
	</script>

	router.replace(location, onComplete?, onAbort?)

        跟 router.push 很像,唯一的不同就是,它不會向 history 添加新記錄,而是跟它的方法名一樣 —— 替換掉當前的 history 記錄




四、命名路由


        有時候,通過一個名稱來標識一個路由顯得更方便一些,特別是在鏈接一個路由,或者是執行一些跳轉的時候。可以在創建 Router 實例的時候,在 routes 配置中給某個路由設置名稱。

  ...
	<!--  注意 to 前面要有 : , 即 v-bind:  -->
	<router-link :to="{ name: 'user'">User</router-link>
  ...
  ...
	var router = new VueRouter({
	  routes: [
	    {
	      path: '/user/:userId',
	      name: 'user',
	      component: User
	    }
	  ]
	})
  ...

要鏈接到一個命名路由,可以給router-link的to屬性傳一個對象:

	<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

這跟代碼調用 router.push() 是一回事:

	router.push({ name: 'user', params: { userId: 123 }})



五、命名視圖


        有時候想同時 (同級) 展示多個視圖,而不是嵌套展示,例如創建一個佈局,有 sidebar(側導航)main(主內容) 兩個視圖,這個時候命名視圖就派上用場了。可以在界面中擁有多個單獨命名的視圖,而不是隻有一個單獨的出口。如果 router-view 沒有設置名字,那麼默認爲 default

	<router-view class="view one"></router-view>
	<router-view class="view two" name="a"></router-view>
	<router-view class="view three" name="b"></router-view>

一個視圖使用一個組件渲染,因此對於同個路由,多個視圖就需要多個組件,使用 components 配置 (帶上s):

    Foo= Vue.extend({template:"<h1>Foo 部分</h1>"})
    Bar= Vue.extend({template:"<h1>Bar 部分</h1>"})
    Baz= Vue.extend({template:"<h1>Baz 部分</h1>"})
	const router = new VueRouter({
	  routes: [
	    {
	      path: '/',
	      components: {
	        default: Foo,
	        a: Bar,
	        b: Baz
	      }
	    }
	  ]
	})



五、重定向和別名


  1. 重定向也是通過 routes 配置來完成,下面例子是從 /a 重定向到 /b
    var article = Vue.extend({template:"<h1>我是文章列表</h1>"})
    var router = new VueRouter({
        routes: [
            // redirect 重定向 
            {path:"/", redirect:"/article"},
            {path:"/article", component: article},
        ]
    })

  1. 重定向的目標也可以是一個命名的路由:
	const router = new VueRouter({
	  routes: [
	    { path: '/a', redirect: { name: 'foo' }}
	  ]
	})

  1. 別名

            “重定向” 的意思是,當用戶訪問 /a 時,URL 將會被替換成 /b,然後匹配 路由/b,那麼 “別名” 又是什麼呢?

            /a 的別名是 /b,意味着,當用戶訪問 /b 時,URL 會保持爲 /b,但是路由匹配則爲 /a,就像用戶訪問 /a 一樣。
	// 上面對應的路由配置爲:
	
	const router = new VueRouter({
	  routes: [
	    { path: '/a', component: A, alias: '/b' }
	  ]
	})


更多內容請參考 vue-router 官方文檔:https://router.vuejs.org/zh/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章