1、在/src/router的index.js文件中配置路由
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import second from '@/components/second'
// 1、引入vue-router
Vue.use(Router)
// 2、定义路由,此处定义了2个路由
const routes = [
{path: '/helloWorld', component: HelloWorld},
{path: '/second', component: second}
]
// 3、实例化Router
const router = new Router({
routes
})
// 4、暴露组件,在mian.js中引入该router
export default router
2、在/src的main.js中导入router
// 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 App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router, //此处调用配置的router
components: { App },
template: '<App/>'
})
3、编写HelloWorld.vue文件
<template>
<div id="vue_det">
<h1>title : {{title}}</h1>
<h1>url : {{url}}</h1>
<h1>msg: {{msg}}</h1>
</div>
</template>
<script>
export default {
name: 'aaa',
data () {
return {
title: 'this is my first vue file',
url: 'www.163.com',
msg: 'Welcome to Your Vue.js App,测试开始'
}
}
}
</script>
<style scoped>
</style>
4、编写second.vue文件
<template>
<div id="vue_det">
<h1>title : {{title}}</h1>
<h1>url : {{url}}</h1>
<h1>msg: {{msg}}</h1>
</div>
</template>
<script>
export default {
name: 'bbb',
data () {
return {
title: 'this is my second vue file',
url: 'www.baidu.com',
msg: 'Welcome to Your Vue.js App,测试开始'
}
}
}
</script>
<style scoped>
</style>
5、启动项目,然后在浏览器中输入路由地址:
http://localhost:8080/#/helloWorld
http://localhost:8080/#/second
6、当然,我们也可以在根节点中直接引用这2个路由。
首先在App.vue中添加代码:
<template>
<div id="app">
<img src="./assets/logo.png">
<h2>{{msg}}</h2>
<router-link to="helloWorld">首页</router-link>
<router-link to="second">第二页</router-link>
<router-link to="/">返回</router-link>
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
data () {
return {
msg: '你好,vue'
}
}
}
</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: 60px;
}
</style>
运行结果如下:
点击首页后页面路由如下:
点击第二页后页面路由如下: