Vue-Router的使用(一)
阿新 • • 發佈:2018-06-19
mat eth sin 一個 ML CI forward 規則 his
1.首先,安裝vue-router
npm install vue-router --save-dev
2.創建一個route.js文件
// 1. 定義路由組件 // 可以自己寫的,或者導入的,大部分是導入的 const Foo = { template: ‘<div>foo</div>‘ } const Bar = { template: ‘<div>bar</div>‘ } // 2. 定義路由規則 // 每個路由映射一個組件 const routes = [ { path: ‘/foo‘, component: Foo }, { path: ‘/bar‘, component: Bar } ]
//導出使用 export default=routes;
3.在入口文件中進行路由的使用
import Vue from ‘vue‘ import VueRouter from ‘vue-router‘ import routes from "./Admin/route/route.js";//導入路由文件 //使用插件 Vue.use(VueRouter) //實例化 const router = new VueRouter({ routes, mode: ‘history‘ }) //使用 new Vue({ el: ‘#app‘, template: "<div><router-view></router-view></div>", router })
4.在組件文件中的使用,獲取參數,跳轉等操作
// Home.vue
<template>
<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>
</template>
<script> 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(‘/‘) } } }
</script>
5.路由方法Api
router.push(location, onComplete?, onAbort?) 例子: const userId = 123 router.push({ name: ‘user‘, params: { userId }}) // -> /user/123 router.push({ path: `/user/${userId}` }) // -> /user/123 // This will NOT work router.push({ path: ‘/user‘, params: { userId }}) // -> /user router.go(n) 例子: // go forward by one record, the same as history.forward() router.go(1) // go back by one record, the same as history.back() router.go(-1)
Vue-Router的使用(一)