Vue:vue-router路由

1.说明

11_13_第六阶段:大前端进阶||07-Vue详解||P15:vue-router路由【router的安装||测试router的跳转】【观看狂神随笔】_Vue


说明:

  • 嵌套的路由/视图表:

2.router的安装

11_13_第六阶段:大前端进阶||07-Vue详解||P15:vue-router路由【router的安装||测试router的跳转】【观看狂神随笔】_Vue_02


vue-router 是一个插件包,所以我们还是需要用 npm/cnpm 来进行安装的。打开命令行工具,进入你的项目目录,输入下面命令:

# 这里我是使用idea控制台使用命令行进行安装的

​cnpm install vue-router --save-dev​​ 验证:查看node_modules中是否存在 vue-router

11_13_第六阶段:大前端进阶||07-Vue详解||P15:vue-router路由【router的安装||测试router的跳转】【观看狂神随笔】_Vue_03

3.测试router的跳转

首先创建一个基础工程

  • 基于vue-cli(vue项目模板)
  • 删除components下的Helloworld.vue
  • 删除app.vue里不需要的部分(如果不删除干净,会报错:This relative module was not found)
  • 得到一个基础工程

(3.1)在component目录下编写vue组件

  • 删除我们不需要的组件
  • 创建Content.vue跟Main.vue两个组件

    Content.vue:
<template>
<h1>内容页</h1>
</template>

<script>
//路由的导出
export default {
name: "Content"
}
</script>

<!--这里的scoped表示下面的样式只能再这个vue里呈现-->
<style scoped>

</style>

Main.vue:

<template>
<h1>首页</h1>
</template>

<script>
//路由的导出
export default {
name: "Main"
}
</script>

<style scoped>

</style>

(3.2)管理路由,在src目录下,新建一个文件夹 : router,专门存放路由

11_13_第六阶段:大前端进阶||07-Vue详解||P15:vue-router路由【router的安装||测试router的跳转】【观看狂神随笔】_vue.js_04


index.js:路由的主配置文件

/*配置路由*/
import Vue from 'vue'
// 导入路由插件
import VueRouter from 'vue-router'
// 导入上面定义的组件
import Content from '../components/Content'
import Main from '../components/Main'

//安装路由
Vue.use(VueRouter);

//配置导出路由
export default new VueRouter({
//前端中,[]是数组,{}是对象
routes: [
{
//路由请求路径
path: '/content',
// 路由名称,可以省略不写
name: 'Content',
//跳转的组件
component: Content
},
{
//路由路径:当请求main路径后,会跳转到Main组件
path: '/main',
// 路由名称,可以省略不写
name: 'Main',
//跳转的组件
component: Main
}
]
});

(3.3)在main.js中配置路由

import Vue from 'vue'
import App from './App'
// 导入上面创建的路由配置目录
import router from './router' //自动扫描里面的路由配置

Vue.config.productionTip = false


new Vue({
el: '#app',
//配置路由
router,
components: { App },
template: '<App/>'
})

(3.4)在app.vue中使用路由

<template>
<div id="app">
<!--
两者缺一不可
router-link: 默认会被渲染成一个 <a> 标签,to 属性为指定链接
router-view: 用于渲染路由匹配到的组件
-->
<h1>Vue-router</h1>
<!--跳转链接:相当于原来的<a>-->
<router-link to="/main">首页</router-link>
<router-link to="/content">内容页</router-link>
<!--展示视图:用来展示templates模板-->
<router-view></router-view>
</div>
</template>

<script>
import HelloWorld from './components/HelloWorld'

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>

(3.5)启动程序

​npm run dev​

11_13_第六阶段:大前端进阶||07-Vue详解||P15:vue-router路由【router的安装||测试router的跳转】【观看狂神随笔】_vue-router_05


11_13_第六阶段:大前端进阶||07-Vue详解||P15:vue-router路由【router的安装||测试router的跳转】【观看狂神随笔】_Vue_06