vue-router教程二(要素篇之新手入門)

注意,咱們將在指南中使用es 2015代碼樣本。此外,全部示例都將使用VUE的完整版原本使在線模板編譯成爲可能。請參閱這裏的更多細節。 php

用vue路由器建立單頁應用程序是很是簡單的。使用vue.js,咱們已經在用組件組合咱們的應用程序。當將vue路由器添加到混合時,咱們所須要作的就是將組件映射到路由,讓vue路由器知道在哪裏呈現它們。下面是一個基本示例:vue

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">
  <h1>Hello App!</h1>
  <p>
    <!-- use router-link component for navigation. -->
    <!-- specify the link by passing the `to` prop. -->
    <!-- `<router-link>` will be rendered as an `<a>` tag by default -->
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <!-- route outlet -->
  <!-- component matched by the route will render here -->
  <router-view></router-view>
</div>

 

JavaScript

// 0. If using a module system (e.g. via vue-cli), import Vue and VueRouter
// and then call `Vue.use(VueRouter)`.

// 1. Define route components.
// These can be imported from other files
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

// 2. Define some routes
// Each route should map to a component. The "component" can
// either be an actual component constructor created via
// `Vue.extend()`, or just a component options object.
// We'll talk about nested routes later.
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = new VueRouter({
  routes // short for `routes: routes`
})

// 4. Create and mount the root instance.
// Make sure to inject the router with the router option to make the
// whole app router-aware.
const app = new Vue({
  router
}).$mount('#app')

// Now the app has started!

經過注入路由器,在任何組件的內部,咱們能夠訪問它。this.$router,以及當前路由。vue-router

// Home.vue
export default {
  computed: {
    username () {
      // We will see what `params` is shortly
      return this.$route.params.username
    }
  },
  methods: {
    goBack () {
      window.history.length > 1
        ? this.$router.go(-1)
        : this.$router.push('/')
    }
  }
}

在整個文檔中,咱們常常使用路由器實例。記住這一點。$router與使用路由器徹底同樣。咱們使用它的緣由是。$router是由於咱們不想在每一個須要操做路由的組件中導入路由器。您也能夠查看這個示例livevee。注意,當一個<router-link> 的目標路由匹配時,它會自動得到.router-link-activeclass。在它的API參考中瞭解更多有關它的信息。vue-cli

相關文章
相關標籤/搜索