vue-router配置

祭出demo: vue-router配置demo

这篇文章介绍的vue-router配置是基于vue-cli脚手架初始化的项目来做的配置,vue-cli脚手架初始化项目请看这里:

Vue.js开发环境搭建

项目初始化完成之后,接下来看这几个步骤:

  1. 配置main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import appVue from './App.vue'//引入app.vue组件
import router from './router/index.js'//引入路由实例

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
 el: '#indexApp',//这里取的是html里的id=indexApp
 router:router,//这里可以写router或者router:router//router模块
 components: { appVue },
 template: '<app-vue></app-vue>'//<appVue/> 或者<app-vue/>都可以。在vue里代码块的定义使用驼峰式时,引入时可以原名字引入也可以通过在每个大写字母前加-引入。
})
/*
main.js自动注入到了index.html里,同时main.js也把App.vue组件的内容引入到index.html里了,App的代码块就是<appVue/>
* */

在main.js里请仔细阅读我的注释,main.js是程序的入口,它关联index.html和App.vue组件并添加app-vue代码模块

2、关注index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>my-first-vue-project</title>
  </head>
  <body>
    <div id="indexApp"></div>
    <!-- 建立的文件将自动注入 -->
    
  </body>
</html>

注意这里的id="indexApp"是和main.js里的el:"#indexApp"是保持一致的。

  1. 关注App.vue
<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
  </div>
</template>

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

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 0px;
}
</style>

<router-view/>就是匹配router中定义的路由模块,其实就是不同的代码块。

  1. 配置router
import Vue from 'vue'
import VueRouter from 'vue-router'//使用路由时,要引入vue-router

import first from '@/components/FirstPage.vue'//引入自己的两个代码块作为自定义组件
import second from '@/components/SecondPage.vue'

// 要告诉 vue 使用 vueRouter
Vue.use(VueRouter)

export default new VueRouter({
    routes: [{
            path: '/',
            component: first,//当访问这个路径'/'时,访问的组件就是first,也就是FirstPage.vue
        },
        {
            path: '/second',
            component: second,//当访问这个路径'/second'时,访问的组件就是second,也就是SecondPage.vue
        },
    ]
})

到此路由配置就完成了,启动项目看到的效果如下图所示:

first.png
second.png

注意事项:

  1. demo中用到的@符号是在webpack.base.conf.js定义,其实是项目的src路径
resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
  1. demo中是没有node_modules文件夹的,因为上传代码时git默认忽略这种公有库的。cd 到demo文件夹 然后执行:npm install就会加载依赖库了。最后npm run dev就可以启动项目

祭出demo: vue-router配置demo

vue-router官方文档

如有错误或疑问,欢迎指正讨论。

参考文章:使用Vue-Router 2实现路由功能vue-router 基本使用

更新时间: 2018-07-13

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值