vue-router
因为Vue是一个专注于视图层的框架,所以要使用vue-router路由来进行转发和重定向
是Vue.js的官方路由管理器,和Vuejs深度集成
包含的功能:
- 嵌套的路由/视图表
- 模块化、基于组件的路由配置
- 路由参数、查询、通配符
- 基于Vue.js过度系统的视图过度效果
- 细粒度的导航控制
- 带有自动激活CSS class的链接
- Html5历史模式或hash模式,在中自动IE9中自动降级
- 自定义的滚动条行为
安装vue-router
-
vue-router
-
检查是否安装
-
npm install vue-router --save-dev
-
安装
vue-router Demo
-
删除点东西
-
HelloWorld删除对应的import和components也删除
-
<template> <div id="app"> </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>
-
整理好的两个文件,作为基础开始学习
-
安装router
-
npm install vue-router --save-dev
-
报出了两个错,按他提示就行调整就行
-
安装好后导入main.js
-
安装的模块都会存放在这个文件夹中,如果进行搜索,是可以搜索到vue-router的
-
显式声明使用
-
前端的导入都是这个形式进行安装的
-
npm run dev
-
启动下项目,就能实时看到页面效果
-
因为自己尝试添加的vue-router无法跳转,所以只能创建项目的时候让它自己创建vue-router了
-
流程:
- 创建一个路由器的核心配置
- 创建几个组件
- 在main添加router
- App设置标签跳转
-
制作一个组件用于跳转,main.vue
-
<template> <h1>haoyun</h1> </template> <script> export default { name: "main" } </script> <style scoped> </style>
-
这个组件就一个功能,显示一个h1标签
-
创建一个文件夹router存放vue-router的配置文件,一般默认起名为index
-
import Vue from 'vue' import Router from 'vue-router' import main from "../components/main"; Vue.use(Router) export default new Router({ routes: [ { path: '/main', name: 'main', component: main } ] })
-
导入vue,vue-router,和组件main,两个点表示上级目录
-
里面编写路径,名字可以不写,对应的component
-
这相当于一个配置文件,然后加载进main中
-
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/>' })
-
App里面要有能跳转的点击事件
-
<template> <div id="app"> <img src="./assets/logo.png"> <router-link to="/main">lin</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>