脚手架实现页面跳转

创建自定义页面

在components添加文件home.vue和about.vue

<template>
 <div>
     <h1>我是首页</h1>
     <p>我是首页内容</p>
 </div>
    
</template>

<script>
export default {
  name:'Home'
}
</script>

<style>

</style>

 

 

<template>
 <div>
     <h2>我是关于页面</h2>
     <p>关于内容页面</p>
 </div>
    
</template>

<script>
export default {
  name:'About'
}
</script>

<style>

</style>

创建路由映射关系

在router文件夹下index.js中添加如下代码

import Vue from 'vue'
import Router from 'vue-router'
import About from '@/components/About'
import Home from '@/components/Home'
import VueRouter from 'vue-router'

// 导入路由对象
Vue.use(Router)
// 创建VueRouter对象
const routes = [
  {
    // 默认值
    path:'',
    redirect:'/home'
  },
  {
    path:'/home',
    component:Home
  },
  {
    path:'/about',
    component:About
  }
]
// 创建路由和组件之间的映射关系
const router = new VueRouter({
  routes,
  mode:'history', // 默认是hash模式
  linkActiveClass:'active' // 激活样式
});

export default router

主页面中添加组件

在App.Vue中添加如下代码

<template>
  <div id="app">
    <h1>我是app首页</h1>
      <router-link to='/home' tag="button" replace>首页</router-link>
      <router-link to='/about' tag="button" replace>关于</router-link>
      <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style>
 .active {
   color: red;
 }
</style>

入口文件

在main.js中添加如下代码

import Vue from 'vue'
import App from './App'
// 省略末尾的index.js
import router from './router' 

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  render:h=>h(App)
})

 手动创建跳转方法

<template>
  <div id="app">
    <h1>我是app首页</h1>

      <button @click="homeClick">首页</button>
      <button @click="aboutClick">关于</button>
      <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  methods:{
    homeClick(){
      // pushstate
      this.$router.push('/home');
    },
    aboutClick() {
       this.$router.push('/about');
    }
  }
}
</script>

<style>
 .active {
   color: red;
 }
</style>

 

posted @ 2020-04-19 16:05  bradleydan  阅读(501)  评论(0)    收藏  举报