一、vue数据响应式原理和双向绑定原理
1). 双向数据绑定是建立在单向数据绑定(model==>View)的基础之上的
2). 双向数据绑定的实现流程:
a. 在解析v-model指令时, 给当前元素添加input监听
b. 当input的value发生改变时, 将最新的值赋值给当前表达式所对应的data属性
二、vue自定义指令(私有,全局)
1.私有自定义指令
自定义指令需要在directives节点下创建私有自定义指令,创建好的指令通过v-指令名放到元素中
2.定义全局自定义属性
全局自定义指令要在main.js下定义,使用Vue.directive() 函数。
详解:
1.什么是自定义事件
vue 官方提供了 v-text,v-for,v-model,v-if 等常用指令。除此之外 vue 还允许开发者自定义指令。
- 私有自定义指令
- 全局自定义指令
(1)私有自定义指令
自定义指令需要在directives节点下创建私有自定义指令,创建好的指令通过v-指令名放到元素中
<template>
<div id="App">
<p v-color>这个文字编程红色</p>
</div>
</template>
<script>
export default {
data() {
return {
}
},
//自定义指令的节点
directives:{
//创建一个color指令,执行配置对象。
color:{
//当指令帮到元素上的时候,聚会出发bind函数
//el参数标识当前绑定的dom对象
bind(el){
el.style.color="red"
}
}
}
}
</script>
上述中,如果给元素添加颜色,只能绑定唯一的值,不能自己设定颜色,
在vue中,可以通过hinding.value获取属性绑定的颜色值。
<template>
<div id="App">
<p v-color='red'>通过属性值绑定的颜色变颜色</p>
<p v-color="'blue'">自己在v-color中自己设置颜色,需要通过字符串形式传入</p>
</div>
</template>
<script>
export default {
data() {
return {
color:'red'
}
},
directives:{
color:{
bind(el,binding){
el.style.color=binding.value
}
}
}
}
</script>
update 函数
bind
函数只调用一次:当指令第一次绑定到元素时调用update
函数会在每次 DOM 更新时被调用update
函数在指令绑定的时候不会被调用!
<template>
<div id="App">
<p v-color='red'>通过属性值绑定的颜色变颜色</p>
<p v-color="'blue'">自己在v-color中自己设置颜色,需要通过字符串形式传入</p>
<button @click="color='blue'">点击变换颜色</button>
</div>
</template>
<script>
export default {
data() {
return {
color:'red'
}
},
directives:{
color:{
//只能被触发一次
bind(el,binding){
el.style.color=binding.value
},
//在每次dom更新的时候触发
update(el,binding){
el.style.color=binding.value
}
}
}
}
</script>
自定义指令的简写形式
简写形式可以包含bind和update两个函数,减少代码的重复,直接将指令变成函数。
<template>
<div id="App">
<p v-color='red'>通过属性值绑定的颜色变颜色</p>
<p v-color="'blue'">自己在v-color中自己设置颜色,需要通过字符串形式传入</p>
<button @click="color='blue'">点击变换颜色</button>
</div>
</template>
<script>
export default {
data() {
return {
color:'red'
}
},
directives:{
//将指令对象改写成指令函数
color(el,binding){
el.style.color=binding.value
}
}
}
</script>
(2)定义全局自定义属性
全局自定义指令要在main.js下定义,使用Vue.directive() 函数。
Vue.directive('color', {
bind(el, binding) {
el.style.color = binding.value
},
update(el, binding) {
el.style.color = binding.value
}
})
或者
这是借助ES6的箭头函数形式
Vue.directive('color', (el,binding)=>el.style.color=binding.value)
三、vue2和vue3区别,以及发生哪些变化
1.生命周期的变化
整体来看,变化不大,只是名字大部分需要 + on
,功能上类似。使用上 Vue3组合式 API 需引入;Vue2 选项 API 则可直接调用,如下所示。
// vue3
<script setup>
import { onMounted } from 'vue'
onMounted(() => {
...
})
// 可将不同的逻辑拆开成多个onMounted,依然按顺序执行,不被覆盖
onMounted(() => {
...
})
</script>
// vue2
<script>
export default {
mounted() {
...
},
}
</script>
常用生命周期表格如下所示。
Vue2.x | Vue3 |
---|---|
beforeCreate | setup( ) |
created | setup( ) |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |