1.首先创建一个vue的项目
如果不知道vue项目环境搭配可以看我上一篇博客链接: link
2.打开创建的vue项目
2.1在components包(也可以在其他地方创建vue文件等会会提到)下面创建两个page.vue文件,下面的三步操作只是为了等会跳转的时候有变化就用了三个vue文件,自己有vue文件的可以跳过。
2.2可以将helloworld文件清空只留下模板 。hellowold.vue文件修改后的代码
<template>
<div class="hello">
<h1>我是hellowrold页</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
2.3同样将page1.vue跟page2.vue写入内容
page1.vue的代码
<template>
<div class="hello">
<h1>我是page1</h1>
<router-link to ="/page1/page2"> page2页</router-link> //根据index.js文件引入的路径来确定link to指向的值。
<router-view/> //它的作用是点击链接后用于显示路径的
</div>
</template>
<script>
export default {
name: 'HelloWorld',
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
page2.vue的代码
<template>
<div class="page2">
<h1>我是page2</h1>
</div>
</template>
<script>
export default {
name: 'page2',
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
三.在index.js中配置路由
在配置路由的时候要注意component对应的变量是import 后面你取值的变量名,并不是你的文件名,这里为了方便展示就将用a1,a2来区分。
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '../components/HelloWorld' //引入helloworld.vue,后面的vue是不用些。
import a1 from '../components/page1' //引入page1.vue
import a2 from '../components/page2' //引入page2.vue
Vue.use(Router)
export default new Router({
routes: [
{
path: '/helloworld',
name: 'HelloWorld', //类名目前还没有用到可以写也可以不写。
component: HelloWorld
},
{
path:'/page1', //配置的路径在首页面展示的都是/page1,如果只有'/'的话就只会展示只是patt'/'对应下面的component指定的页面。
component:a1,
children:[{path:'/page1/page2',component:a2}] //引入子路径 pata=‘/父路径的path/子文件名’。
}
]
})
在app.vue中 ,app是默认进入的首页,之后再app这一页当中通过点击不同的链接跳转到不同的页面,或者说进行不同渲染。跳转的渲染模块效果如何跟原页面在相同位置都有渲染的话就会把原页面覆盖。
<template>
<div id="app">
<h1>我是app页面</h1>
<router-link to ="/helloworld"> 点我进入helloworld页</router-link>
<router-link to ="/page1"> 点我进入page1页</router-link>
<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: 60px;
}
</style>
效果展示
今天写子路由的时候只是在app.vue文件中有写到,在page1.vue中没有写导致在page1页面不能跳转到page2中。
<router-view/>
在index.js中引入路径时是更具你vue文件的具体位置。
学习vue的第二天今天的收获就写到这里了。