「这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战」。
vue2
首先我们先回顾一下vue2中几个比较重要的知识点。
什么是MVVM?
1、M 模型(Model):对应data中的数据。
2、V 视图(view):对应模板。
3、VM 视图模型(viewModel):Vue实例对象。
生命周期
官方图其实很清楚了,就是开始创建到销毁的过程。
另外还有两个钩子:
activated:被 keep-alive 缓存的组件激活时调用。
deactivated:被 keep-alive 缓存的组件失活时调用。
errorCaptured:在捕获一个来自后代组件的错误时被调用
组件
一、vue组件分为局部组件和全局组件。
局部组件引入方式:
new Vue({
el: '#app',
components: {
'component-a': ComponentA,
'component-b': ComponentB
}
})
---or---
import ComponentA from './ComponentA.vue'
export default {
components: {
ComponentA
},
// ... }
全局组件引入方式:
Vue.component('my-component-name', { /* ... */ })
二、组件缓存
<!-- 失活的组件将会被缓存!-->
<keep-alive>
<component v-bind:is="currentTabComponent"></component>
</keep-alive>
三、组件的异步加载
'my-component'() => import('./my-async-component')
四、组件的传值
父传子:子组件通过props接收||或者通过$refs方式传值
子传父:通过$emit事件回调传值
全局事件总线:
注册
Vue.protype.`$bus`=new Vue()
监听
this.$bus.$on('event', callback)
触发
this.$bus.$emit('eventName', [...args])
移除
vm.$off( [event, callback] )]
插槽slot
子组件
<slot></slot>
父组件
<child>-插槽内容显示在子slot-</child>
//具名插槽
子组件
<slot name="name"></slot>
父组件
<template v-slot:[name]></tepmlate>
vuex
vuex的五个属性分别为:state、getters、 mutations、actions、modules。
重要点:
1、更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。
2、Action 处理异步操作。
3、modules,分割模块。
4、辅助函数mapState mapGetters mapMutations mapActions
5、vuex状态为响应式,读取使用一般使用computed
路由
跳转:this.$router.push <router-link to="">
获取参数:this.$route.params this.$route.query
ps:params和query都是传递参数的,params不会在url上面出现。有点像get和post哈。
嵌套路由:使用children参数,component
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User,
children: [
{
// 当 /user/:id/profile 匹配成功,
// UserProfile 会被渲染在 User 的 <router-view> 中
path: 'profile',
component: UserProfile
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 会被渲染在 User 的 <router-view> 中
path: 'posts',
component: UserPosts
}
]
}
]
})
路由模式:
两种hash和history,通过router.mode配置。
导航守卫:
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
可以通过导航守卫做路由权限管理这块操作。
路由懒加载
通过cli构建的项目,我们一般使用import引入组件的方式来实现懒加载。
const Foo = () => import('./Foo.vue')
const router = new VueRouter({
routes: [
{ path: '/foo', component: Foo)
}
]
})
自定义指令
定义和使用:Vue.directive( id, [definition] )]
钩子函数有:bind、inserted、update、componentUpdated、unbind
钩子函数的参数:el、bind、vnode、oldVnode
创建:多个组件定义方式,我们一般创建单独文件export。
export default {...}
引入:
import directive from 'directive.js'
Object.keys(directive).forEach((fncName) => {
Vue.directive(fncName, directive[fncName])
})
过滤器
定义:
Vue.filter('capitalize', function (value) {
return ...
})
使用:
{{ message | capitalize }}
--or--
<div v-bind:id="rawId | formatId"></div>
结尾
自我梳理。嗯!晚了,明天继续