Vue配置路由

134 阅读1分钟

1. 创建项目

打开文件夹,在路径栏里面输入cmd, 打开cmd命令行,输入 vue create 文件名。 依次操作,最后输入y,回车,成功创建项目。

image.png

2. src>router>index.js

/* 导入Vue构造函数 */
import Vue from 'vue'
/* 导入VueRouter构造函数 */
import VueRouter from 'vue-router'
/* 导入HomeView页面 */
import HomeView from '../views/HomeView.vue'

/* 调用构造函数Vue的use方法 传入VueRouter构造函数 
作用是:把VueRouter当作一个插件 全局插入到Vue中*/
Vue.use(VueRouter)

/* 定义一个路由数组对象 */
const routes = [
  /* 一个对象就对应了一个路由
  path就是路由的地址
  name给路由起个名字
  component就是具体跳转的页面
  */
  {
    /* path: '/' 表示根路径 一进入页面跳转的组件 */
    path: '/',
    name: 'home',
    component: HomeView  
  },
  {
    /* 这里是一级目录所以可以加/, /表示根目录 */
    path: '/about',
    name: 'about',
    /* 箭头函数的写法可以实现‘懒加载’的效果 */
    component: () => import('../views/AboutView.vue'),
  }
]

/* 实例化构造函数VueRouter 产生一个实例化对象router 
并把上面的路由数组对象routes当作参数 以对象的方式传给构造函数VueRouter*/
const router = new VueRouter({
  routes: routes
})

/* 把实例化路由对象router默认导出 */
export default router
复制代码
复制代码

3. src>main.js

/* 导入Vue构造函数 */
import Vue from 'vue'
/* 导入App.vue入口页面 */
import App from './App.vue'
/* 导入router文件夹index.js中的router实例化对象 */
/* 一个文件夹里面只有一个index.js文件在脚手夹中可以把./router/index.js简写为./router */
import router from './router'

/* 改成false是用来关闭开发者提示 */
Vue.config.productionTip = false

/* 在Vue的对象参数里面配置el:"#app"的作用和.$mount('#app')一致
都是用来挂载到id为#app的div上的 */
/* 把路由实例化对象router配置在Vue中,作用是保证项目中所有的
vue文件都可以使用router路由的属性和方法 */
/* render: h => h(App) 会把所有的vue文件渲染到App组件上 */
new Vue({
  router:router,
  render: h => h(App)
}).$mount('#app')