17.编程式导航(js驱动跳转)和路由的hash模式与History模式
编程式导航
与router-link导航相比,router-link类似于a标签,编程式导航相当于ajax,导航用页面跳转
Home.vue
<template> <div> <h2>{{msg}}</h2> <br> <button @click="goNew()">通过js跳转到新闻页面</button> <br> </div> </template> <script> export default { name: 'home', data () { return { msg:'首页组件' } }, methods:{ goNew(){ // this.$router.push({path:'news'}) this.$router.push({path:'vcontent/0'}) } }, components:{ } } </script> <style lang="scss" scoped> h2{ color: red; } </style>
hash模式与History模式
在main.js中加入:
mode:'history',//hash改为history模式
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'; import vContent from './components/vContent.vue'; import Good from './components/Goods.vue'; // 2.配置路由 const routes=[ {path:'/home',component:Home}, {path:'/news',component:News}, {path:'/vcontent/:aid',component:vContent}, //动态路由 {path:'*',redirect:'/home'}, //默认路由跳转到首页 {path:'/goods',component:Good}, ] //注意,这里是routes,而不是routers // 3.实例化VueRouter const router=new VueRouter({ mode:'history',//hash改为history模式 routes//(缩写)相当于routers:routers }) // 4.挂载 new Vue({ el: '#app', router, render: h => h(App) }) // 5.将<router-view></router-view>放在App.vue里面