Vue
vue介绍
- vue 中文网
- Vue.js 是什么
- 介绍:Vue是一套用于构建用户界面的渐进式框架。
基础入门
- 安装:
npm install vue
- 通过
new Vue()创建vue实例,并且指定el和data参数 - 在页面中,通过
{{ }}访问数据
// 2. 创建vue实例,需要指定el和data属性
let vm = new Vue({
// 指定vue监管的视图区域,只要id为app的div内部才会受vue的管理
el: '#app',
// 提供了vue中使用的数据
data: {
msg: 'hello vue'
}
})
注意:el不能是html和body
Vue-router
Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:
- 嵌套的路由/视图表
- 模块化的、基于组件的路由配置
- 路由参数、查询、通配符
- 基于 Vue.js 过渡系统的视图过渡效果
- 细粒度的导航控制
- 带有自动激活的 CSS class 的链接
- HTML5 历史模式或 hash 模式,在 IE9 中自动降级
- 自定义的滚动条行为
vue-router核心代码:
App.vue
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/ablout">About</router-link>
</div>
<router-view/>
</div>
</template>
123456789
router/index.js
// 注册插件
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
}
]
const router = new VueRouter({
routes
})
export default router
123456789101112131415161718192021
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
const vm = new Vue({
router,
render: h => h(App)
}).$mount('#app')
console.log(vm)
123456789101112
一、动态路由
router/index.js
const routes = [
{
path: '/',
name: 'Index',
component: Index
},
{
path: '/detail/:id',
name: 'Detail',
// 开启props,会把URL中的参数传递给组件
props: true,
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/Detail.vue')
}
]
123456789101112131415161718
view/Detail.vue
<template>
<div>
这是Detail页面
<!-- 方式一:通过当前路由规则,获取数据 -->
通过当前路由规则获取:{{ $route.params.id }}
<br>
<!-- 方式二:路由规则中开启props传参 (推荐)-->
通过开启props获取: {{ id }}
</div>
</template>
<script>
export default {
name: 'Detail',
// 将路由参数配置到props中
props: ['id']
}
</script>
123456789101112131415161718192021
二、嵌套路由
router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../components/Layout.vue'
import Login from '../views/Login.vue'
import Index from '../views/Index.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/login',
name: 'login',
component: Login
},
// 嵌套路由
{
path: '/',
component: Layout,
children: [
{
path: '',
name: 'index',
component: Index
},
{
path: 'detail/:id',
name: 'detail',
props: true,
component: () => import('@/views/Detail.vue')
}
]
}
]
const router = new VueRouter({
routes
})
export default router
12345678910111213141516171819202122232425262728293031323334353637383940
components/Layout.vue
<template>
<div>
<div>
<img width='80px' src='@/assets/logo.png'>
</div>
<div>
<router-view></router-view>
</div>
<div>
Footer
</div>
</div>
</template>
12345678910111213
三、编程式导航
View/Index.vue
<template>
<div>
<router-link to="/">首页</router-link>
<button @click="replace"> replace </button>
<button @click="goDetail"> Detail </button>
</div>
</template>
<script>
export default {
name: 'Index',
methods: {
replace () {
this.$router.replace('/login')
},
goDetail () {
this.$router.push({ name: 'Detail', params: { id: 1 } })
}
}
}
</script>
12345678910111213141516171819202122
View/Detail.vue
<template>
<div>
这是Detail页面
路由参数: {{ id }}
<button @click="go"> go(-2) </button>
</div>
</template>
<script>
export default {
name: 'Detail',
// 将路由参数配置到props中
props: ['id'],
methods: {
go () {
this.$router.go(-2)
}
}
}
</script>
1234567891011121314151617181920212223
四、Hash模式和History模式
1. 表现形式的区别
- Hash模式:http://localhost/#/detail?id=1234
- History模式:http://localhost/detail/1234
2. 原理的区别
- Hash模式是基于锚点,以及onHashChange事件。
- History模式是基于HTML5中的History API
- History.pushState() IE10以后才支持
- History.replaceState()
3. History模式的使用
-
History需要服务器的支持
-
单页应用中,服务端不存在www.test.com/login这样的地址会…
-
在服务端应该除了静态资源外都返回单页应用的index.html
-
Node.js服务器配置
const path = require('path') // 导入处理 history 模式的模块 const history = require('connect-history-api-fallback') // 导入 express const express = require('express') const app = express() // 关键:注册处理 history 模式的中间件 app.use(history()) // 处理静态资源的中间件,网站根目录 ../web app.use(express.static(path.join(__dirname, '../web'))) // 开启服务器,端口是 3000 app.listen(3000, () => { console.log('服务器开启,端口:3000') }) 12345678910111213141516 -
Nginx服务器配置
# 启动 start nginx # 重启 nginx -s reload # 停止 nginx -s stop 123456
nginx.conf
http: {
server: {
location / {
root html;
index index.html index.htm;
# 尝试查找,找不到就回到首页
try_files $uri $uri/ /index.html;
}
}
}
12345678910
4. Hash模式
- URL中#后面的内容作为路径地址
- 监听hashchange事件
- 根据当前路由地址找到对应组件重新渲染
5. History模式
- 通过History.pushState()方法改变地址栏(不会向服务器发送请求,但会将这次URL记录到历史中)
- 监听popstate事件
- 根据当前路由地址找到对应组件重新渲染
五、实现自己的vue-router
Vue的构建版本
-
运行时版:不支持template模板,需要打包的时候提前编译
-
使用render函数
Vue.component('router-link', { props: { to: String }, render (h) { return h('a', { attrs: { href: this.to }, }, [this.$slots.default]) }, // template: '<a href="to"><slot></slot></a>' }) 1234567891011121314
-
-
完整版:包含运行时和编译器,体积比运行时版本大10k左右,程序运行的时候把模板转换成render函数
-
在项目根目录下增加一个文件:vue.config.js
module.exports = { // 完成版本的Vue(带编译器版) runtimeCompiler: true } 1234
-
最终代码:
Vuerouter/index.js
let _Vue = null
export default class VueRouter {
static install (Vue) {
// 1. 判断当前插件是否已经被安装
if (VueRouter.install.installed) return
VueRouter.install.installed = true
// 2. 把Vue构造函数记录到全局变量
_Vue = Vue
// 3. 把创建Vue实例时候传入的router对象注入到Vue实例上
// 混入
_Vue.mixin({
beforeCreate () {
if (this.$options.router) {
_Vue.prototype.$router = this.$options.router
this.$options.router.init()
}
}
})
}
constructor (options) {
this.options = options
this.routeMap = {}
// _Vue.observable创建响应式对象
this.data = _Vue.observable({
current: '/'
})
}
init () {
this.createRoutMap()
this.initComponents(_Vue)
this.initEvent()
}
createRoutMap () {
// 遍历所有的路由规则,把路由规则解析成键值对的形式,存储到routeMap中
this.options.routes.forEach(route => {
this.routeMap[route.path] = route.component
})
}
initComponents (Vue) {
Vue.component('router-link', {
props: {
to: String
},
render (h) {
return h('a', {
attrs: {
href: this.to
},
// 事件
on: {
click: this.clickHandler
}
}, [this.$slots.default])
},
methods: {
clickHandler (e) {
history.pushState({}, '', this.to)
this.$router.data.current = this.to
e.preventDefault()
}
}
// template: '<a href="to"><slot></slot></a>'
})
const self = this
Vue.component('router-view', {
render (h) {
const component = self.routeMap[self.data.current]
return h(component)
}
})
}
initEvent () {
window.addEventListener('popstate', () => {
this.data.current = window.location.pathname
})
}
}
Router/index.js
// ....
import VueRouter from '../vuerouter'
// ....
代码仓库: gitee.com/michengmeng…
结语 文章中可能会有很多错误,如果出现了错误请大家多多包涵指正(/手动狗头保命/),我也会及时修改,希望能和大家一起成长。
下一章,手写Vue响应式实现。