前言:学习自https://www.bilibili.com/video/BV18E411a7mC?p=15
文章目录
【Vue 路由】
一、初始化项目
1、vue init webpack 项目名:创建一个基于 webpack 模板的新项目
2、同意安装 vue-router (如果选了否,那么需要自己在项目创建完后,打开命令行工具,进入项目目录,用 npm install vue-router --save -dev 来手动安装,并且安装完后还要自己去项目 src 目录下新建 router 目录,并创建自己路由配置文件 index.js 才能进行路由配置编写与操作,因此很麻烦,如此一对比,借助 Vue 的脚手架就简便多了)
二、删除自带的组件
为了便于测试,先删除官方自带的组件例子和与之相关的代码,并建立自己的文件结构来测试
src 目录结构:
三、路由例子编写
1、定义组件(components 目录下)
Content.vue
<template>
<h1>内容页</h1>
</template>
<script>
export default {
name: "Content"
}
</script>
<style scoped>
</style>
Main.vue
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
2、配置路由(router 目录下的 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
},
{
path: '/main',
component: Main
}
]
})
或
import VueRouter from 'vue-router'
import Content from "../components/Content";
import Main from "../components/Main";
export default new VueRouter({
routes: [
{
path: '/content',
name: 'content',
component: Content
},
{
path: '/main',
component: Main
}
]
})
3、导入路由到 main.js(main.js 文件)
import Vue from 'vue'
import App from './App'
import router from './router'
import VueRouter from "vue-router";
Vue.config.productionTip = false
Vue.use(VueRouter);
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
4、使用路由(App.vue)
<template>
<div id="app">
<h1>Zhou_LC</h1>
<router-link to="/main">首页</router-link>
<router-link to="content">内容页</router-link>
<router-view></router-view>
</div>
</template>
<script>
import Content from "./components/Content";
export default {
name: 'App',
comments: {
Content
}
}
</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>
5、附:index.html 不用改动
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>my-router</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
四、效果展示
点击首页
点击内容页
【参数传递】
方式一
1、路由时传递参数
(传递参数,就需要用对象,因此需要 v-bind 绑定)
2、嵌套路由 children 属性,path 路径中指定参数
3、在 vue 组件中渲染数据
外层须有 div,不然渲染数据时可能会报错
方式二
1、路由时传递参数
(传递参数,就需要用对象,因此需要 v-bind 绑定)
2、嵌套路由 children 属性,path 路径中指定参数,并令 porps 属性为 true
3、在 vue 组件中渲染数据
外层须有 div,不然渲染数据时可能会报错
【路由模式】
【实现404页面】
在 router/index.js 文件中路由配置的最下面,配置 path: ‘*’ 的404页面组件,即可实现。