15.vue中的路由vue-router
vue路由配置:
1.安装
npm install vue-router --save / cnpm install vue-router --save
2.引入并Vue.use(VueRouter) (main.js)
import VueRouter from 'vue-router';
Vue.use(VueRouter)
3.配置路由
1.创建组件,引入组件
import Home from './components/Home.vue';
import News from './components/News.vue';
2.定义路由
const routes=[ {path:'/home',component:Home}, {path:'/news',component:News}, {path:'*',redirect:'/home'} //默认路由跳转到首页 ] //注意,这里是routes,而不是routers
3.实例化VueRouter
const router=new VueRouter({
routes//(缩写)相当于routes:routes
})
4.挂载
new Vue({
el: '#app',
router,
render: h => h(App)
})
5.在根组件中放入
<router-view></router-view>
6.在根组件中可以通过router-link进行路由的跳转
<router-link to="/home">首页</router-link> <router-link to="/news">新闻</router-link>
代码
1.在main.js中:
import Vue from 'vue'; import App from './App.vue'; import VueResource from 'vue-resource'; Vue.use(VueResource) import VueRouter from 'vue-router'; Vue.use(VueRouter) // 1.创建组件,导入组件 import Home from './components/Home.vue'; import News from './components/News.vue'; // 2.配置路由 const routes=[ {path:'/home',component:Home}, {path:'/news',component:News}, {path:'*',redirect:'/home'} //默认路由跳转到首页 ] //注意,这里是routes,而不是routers // 3.实例化VueRouter const router=new VueRouter({ routes//(缩写)相当于routers:routers }) // 4.挂载 new Vue({ el: '#app', router, render: h => h(App) }) // 5.将<router-view></router-view>放在App.vue里面
2.在App.vue中
<template> <div id="app"> <h2>{{msg}}</h2> <router-view></router-view> <router-link to="/home">首页</router-link> <router-link to="/news">新闻</router-link> </div> </template> <script> export default { name: 'app', data () { return { msg:'根组件' } }, methods:{ }, } </script> <style> </style>