Vue Router 的多種用法

組成部分:https://router.vuejs.org/zh/api/#routes

1、地址  --  path;

2、渲染內容(加載內容)--  component;

     const 定義的對象:User、UserHome、UserProfile、UserPosts

3、嵌套路由  --  children;

 

聲明式 編程式
<router-link :to="..."> router.push(...)

 

例如:

Html內容:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <p>
    <router-link to="/user/foo/ss">/user/foo/ss</router-link>
  </p>
  <p>
    <router-link to="/user/foo/profile22/profile">/user/foo/profile</router-link>
  </p>
  <p>
    <router-link to="/user/foo/posts11/posts">/user/foo/posts</router-link>
  </p>
  <router-view></router-view>
</div>

 

JS內容:

const User = {
  template: `
    <div class="user">
      <h2>User {{ $route.params.id }} {{ $route.params.id1 }}</h2>
      <router-view></router-view>
    </div>
  `
}

const UserHome = { template: '<div>Home</div>' }
const UserProfile = { template: '<div>Profile</div>' }
const UserPosts = { template: '<div>Posts</div>' }

const router = new VueRouter({
  routes: [
    { path: '/', component: UserHome },
    { path: '/user/foo', component: UserHome },
    { path: '/user/:id/:id1', component: User,
      children: [
        // UserHome will be rendered inside User's <router-view>
        // when /user/:id is matched
            { path: '/', component: UserHome },
                
        // UserProfile will be rendered inside User's <router-view>
        // when /user/:id/profile is matched
        { path: 'profile', component: UserProfile },

        // UserPosts will be rendered inside User's <router-view>
        // when /user/:id/posts is matched
        { path: 'posts', component: UserPosts }
      ]
    }
  ]
})
const app = new Vue({ router }).$mount('#app')

 

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