vue part4 vue-router
Posted infaaf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue part4 vue-router相关的知识,希望对你有一定的参考价值。
文档 https://router.vuejs.org/zh-cn
npm install vue-router --save
调用
import Vue from ‘vue‘ import VueRouter from ‘vue-router‘ Vue.use(VueRouter)
流程
a. views目录内组件
b. router目录映射路由js (路径与a中组件)
c. main.js 对象属性router
d. 标签router-link / router-view
1.基本路由
index.html
routeview 标签选中自带class .router-link-active ,定义样式
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="stylesheet" href="./static/css/bootstrap.css"> <title>vue_demo</title> <style> .router-link-active { color: red !important; } </style> </head> <body> <div id="app"> </div> <!--app --> </body> </html>
views/About.vue
与路由相关组件放置与views目录下
<template>
<div>about</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
views/Home.vue
<template>
<div>home</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
router/index.js
绑定path与对应views下的组件
/** * Created by infaa on 2018/9/21. */ import Vue from ‘vue‘ import VueRouter from ‘vue-router‘ import About from ‘../views/About.vue‘ import Home from ‘../views/Home.vue‘ Vue.use(VueRouter) export default new VueRouter({ routes: [ { path: ‘/about‘, component: About }, { path: ‘/home‘, component: Home }, { path: ‘/‘, redirect: ‘/about‘ } ] })
app.js
使用router 方法,利用router-link to=‘‘xxx“区分 ,router-view 自动匹配到views下的组件
<template> <div> <div class="row"> <div class="col-xs-offset-2 col-xs-8"> <div class="page-header"><h2>Router Basic - 01</h2></div> </div> </div> <div class="row"> <div class="col-xs-2 col-xs-offset-2"> <div class="list-group"> <router-link to="/about" class="list-group-item">About</router-link> <router-link to="/home" class="list-group-item">Home</router-link> </div> </div> <div class="col-xs-6"> <div class="panel"> <div class="panel-body"> <router-view></router-view> </div> </div> </div> </div> </div> </template> <script> export default { } </script> <style> </style>
main.js 需要注册router
/** * Created by infaa on 2018/9/19. */ import Vue from ‘vue‘ import App from ‘./App‘ import router2 from ‘./router‘ /* eslint-disable no-new */ new Vue({ el: ‘#app‘, components: {App}, template: ‘<App/>‘, router: router2 })
以上是关于vue part4 vue-router的主要内容,如果未能解决你的问题,请参考以下文章