vue-router的使用

使用vue-cli构建项目结构,里面默认会用到vue-router,从而实现页面路由跳转。

main.js内容如下:

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

其中,构建Vue实例的时候加入了router,而router的内容来自于router文件夹下的index.js文件。

Vue项目的入口文件是main.js,然后根据Vue实例,渲染App.vue。

App.vue内容如下,其中<router-view>是路由跳转更换的内容页面。

在页面挂载的时候,用this.$router.push()函数跳转到Home页面。

<template>
  <div>
    <center class="name">幸运大抽奖</center>
    <img src="@/assets/bg.jpeg" alt="" class="bg">
    <router-view id="app"></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  mounted() {
    this.$router.push('/Home')
  }
}
</script>

<style>
.name{
  font-size: 40px;
  letter-spacing: 0.8em;
  margin-left: 0.8em;
  margin-top: 80px;
  font-family: "Arial","Microsoft YaHei","黑体","宋体",sans-serif;
  font-weight: bold;
}
.bg{
  width: 100%;
  min-height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
}
</style>

假设我有三个页面Home、Draw、Config需要跳转,则需可以在router/index.js中配置路由如下:

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Draw from '@/components/Draw'
import Config from '@/components/Config'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/Home',
      name: 'Home',
      component: Home
    },
    {
      path: '/Draw',
      name: 'Draw',
      component: Draw
    },
    {
      path: '/Config',
      name: 'Config',
      component: Config
    },
  ]
})

配置好后用this.$router.push()函数即可实现路由跳转。

posted @ 2021-05-07 09:24  罗毅豪  阅读(64)  评论(0编辑  收藏  举报