Vue 基础知识总结
MVVM
MVVM是MVC演变过来的一种架构,M是Model层代表数据类型,V是View层代表视图,VM是View Model层是View和Model之间的桥梁。当View或Model层发生改变是,通知View Model层去更新数据。
Vue 生命周期
Vue 实例的创建过程,在创建实例的过程中 Vue 会提供一些钩子函数,以便我们在创建实例的过程中完成某些事情
-
Create 阶段
-
Mount 阶段
-
BeforeUpdate:响应式数据更新时调用,虽然数据更新了,但是此时还没有替换页面中的 html
-
Update:响应式数据更新后,html 页替换了页面后调用
-
BeforeDestory:组件销毁前调用
-
Destoryed:组件销毁后调用
-
activated: keep-alive 所有的生命周期,激活缓存组件时调用
-
deactivated: keep-alive 所有的生命周期,缓存组件时调用
Vue 父子组件生命周期执行顺序
渲染过程
- 父 beforeCreated
- 父 created
- 父 beforeMount
- 子 beforeCreated
- 子 created
- 子 beforeMount
- 子 mounted
- 父 mounted
更新过程
- 父 beforeUpdate
- 子 beforeUpdate
- 子 updated
- 父 updated
销毁过程
- 父 beforeDestory
- 子 beforeDestory
- 子 destoryed
- 父 destoryed
组件通信
props/emit
{
props: {
test: {
type: Object,
value: {}
}
}
}
<ChildComp :test="obj">
子组件向父组件传值
<ChildComp @data="(data) => { console.log(data) }">
{
data: {
test: "test"
},
mounted() {
this.$emit("test", { test: this.test })
},
}
事件总线 EventBus
通过一个 vue 实例的 $emit/$on 在父/子,非父子之间传递数据
import Vue from "vue";
export const EventBus = new Vue();
两个兄弟节点 childA 和 childB 模拟 A 向 B 发送数据
import { EventBus } from 'eventbus.js'
{
mounted() {
EventBus.$emit("postData", { data: "test" })
}
}
import { EventBus } from 'eventbus.js'
{
mounted() {
EventBus.$on("postData", (data) => {
console.log(data.data)
})
}
}
当维护一个庞大的项目时,这种方法就会维护起来非常复杂
Provide/inject
通过依赖注入的方法向子组件传递数据
provice() {
return {
data: "test"
}
}
inject: ["data"]
ref/$refs
-
ref: 在子组件中使用,用于表示此子组件实例
-
$refs: 获取所有标记了的子组件实例
<template>
<ChildComp ref="child">
</template>
<script>
export default {
mounted() {
this.$refs.child
}
}
</script>
$parent/$children
$attrs/$listen
用于深层次组件嵌套获取父组件属性和事件
<template>
<ChildA dataA="testA" dataB="testB" @clickA="clickA" @clickB="clickB" />
</template>
<script>
export default {
methods: {
clickA() {
console.log("trigger A")
},
clickB() {
console.log("trigger B")
},
}
}
// 子组件A
<template>
<ChildB v-bind="$attrs" v-on="$listeners" />
<template>
<script>
export default {
props: ["dataA"],
inheritAttrs: false,
mounted() {
this.$emit("clickA")
}
}
// 子组件B
<template>
<p>{dataB}</p>
</template>
<script>
export default {
props: ["dataB"]
inheritAttrs: false,
mounted() {
this.$emit("clickB")
}
}
</script>
</script>
</script>