Vue2&3
- 基礎性
- 1. 關於Vue2和Vue3生命週期的差別
- 2. Vue2&3組件之間傳參不同點
- Vue2 傳遞與接收
- Vue3 傳遞與接收 (使用script setup語法糖)
- Vue3 傳遞與接收 (不使用script setup語法糖)
- 3. Vue2&3 keep-alive 組件
- Vue2 keep-alive
- Vue3 keep-alive
- 進階性
- 爲什麽POST請求有時會重複調用兩次
- 網路問題
- 跨域請求與預檢請求
- JS原型、原型鏈
- 原型
- 原型鏈
- 繼承 有哪些繼承 優點是什麼
- new 操作符具体干了什么
- js 有哪些方法改变 this 指向
- 对一个函数链式调用 bind,this 指向的是谁?为什么?
整個内容一般都是講Vue2&3的不同點 并無單個版本説明
博客為 >>星光菌子
整理
基礎性
1. 關於Vue2和Vue3生命週期的差別
-
相似的生命周期阶段
Vue 2
和Vue 3
都包含以下几个核心的生命周期阶段,且对应的钩子函数功能类似 -
创建阶段:在实例初始化时触发,主要用于初始化数据和事件
Vue 2
:beforeCreate 和 created
Vue 3
:beforeCreate 和 created
不过在 Vue 3 的组合式 API 里,beforeCreate 和 created可以省略
,因为 setup 函数在这个阶段之前执行,能完成相同的初始化工作 -
挂载阶段:在实例挂载到 DOM 之前和之后触发
Vue 2
:beforeMount 和 mounted
Vue 3
:beforeMount 和 mounted
功能与 Vue 2 一致 -
更新阶段:当响应式数据发生变化,DOM 重新渲染前后触发
Vue 2
:beforeUpdate 和 updated
Vue 3
:beforeUpdate 和 updated
功能与 Vue 2 一致 -
销毁阶段:在实例销毁前后触发,用于清理一些资源
Vue 2
:beforeDestroy(Vue 2.2.0 起也叫 beforeUnmount) 和 destroyed(Vue 2.2.0 起也叫 unmounted)
Vue 3
:beforeUnmount 和 unmounted
beforeUnmount 替代了 Vue 2 的 beforeDestroy,unmounted 替代了 destroyed
2. Vue2&3組件之間傳參不同點
在 Vue 2
和 Vue 3
中,组件之间传参主要有两个明显不同点
-
声明方式:
Vue 2
在组件选项中使用props
选项以对象或数组形式声明接收的属性;Vue 3
在script setup
中使用 defineProps 宏函数来声明,在普通script
中使用和Vue 2
类似的props
选项
-
事件监听:
Vue 2
使用$emit
触发自定义事件,父组件使用v-on
或@
监听;Vue 3
在script setup
中使用defineEmits
宏函数声明可触发的事件,触发方式和Vue 2
类似,但语法更简洁
Vue2 傳遞與接收
# 父组件 Parent.vue
<template>
<div>
<!-- 引入子组件并传递数据,同时监听子组件触发的事件 -->
<ChildComponent :message="parentMessage" @childEvent="handleChildEvent" />
</div>
</template>
<script>
// 引入子组件
import ChildComponent from './Child.vue';
export default {
components: {
ChildComponent
},
data() {
return {
// 父组件的数据,用于传递给子组件
parentMessage: '来自 Vue 2 父组件的数据'
};
},
methods: {
// 处理子组件触发的事件的方法
handleChildEvent(data) {
console.log('在 Vue 2 中收到来自子组件的数据:', data);
}
}
};
</script>
# 子组件 Child.vue
<template>
<div>
<!-- 显示从父组件接收到的数据 -->
<p>{{ message }}</p>
<!-- 点击按钮触发向父组件发送事件 -->
<button @click="sendEventToParent">向父组件发送事件</button>
</div>
</template>
<script>
export default {
// 声明接收父组件传递的 props
props: ['message'],
methods: {
// 触发向父组件发送事件的方法
sendEventToParent() {
// 触发自定义事件并传递数据给父组件
this.$emit('childEvent', '来自 Vue 2 子组件的数据');
}
}
};
</script>
Vue3 傳遞與接收 (使用script setup語法糖)
# 父组件 Parent.vue
<template>
<div>
<!-- 引入子组件并传递数据,同时监听子组件触发的事件 -->
<ChildComponent :message="parentMessage" @child-event="handleChildEvent" />
</div>
</template>
<script setup>
import { ref } from 'vue';
// 引入子组件
import ChildComponent from './Child.vue';
// 使用 ref 创建响应式数据,作为要传递给子组件的数据
const parentMessage = ref('来自 Vue 3 父组件的数据');
// 处理子组件触发的事件的方法
const handleChildEvent = (data) => {
console.log('在 Vue 3 中收到来自子组件的数据:', data);
};
</script>
# 子组件 Child.vue
<template>
<div>
<!-- 显示从父组件接收到的数据 -->
<p>{{ message }}</p>
<!-- 点击按钮触发向父组件发送事件 -->
<button @click="sendEventToParent">向父组件发送事件</button>
</div>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
// 声明接收父组件传递的 props
const props = defineProps({
message: String
});
// 声明可触发的自定义事件
const emits = defineEmits(['child-event']);
// 触发向父组件发送事件的方法
const sendEventToParent = () => {
// 触发自定义事件并传递数据给父组件
emits('child-event', '来自 Vue 3 子组件的数据');
};
</script>
Vue3 傳遞與接收 (不使用script setup語法糖)
# 父组件 Parent.vue
<template>
<div>
<!-- 引入子组件,传递数据并监听子组件触发的事件 -->
<ChildComponent :message="parentMessage" @child-event="handleChildEvent" />
</div>
</template>
<script>
import { ref } from 'vue';
// 引入子组件
import ChildComponent from './Child.vue';
export default {
components: {
ChildComponent
},
setup() {
// 使用 ref 创建响应式数据
const parentMessage = ref('来自 Vue 3 父组件的数据');
// 处理子组件触发的事件的方法
const handleChildEvent = (data) => {
console.log('在 Vue 3 中收到来自子组件的数据:', data);
};
// 返回需要在模板中使用的数据和方法
return {
parentMessage,
handleChildEvent
};
}
};
</script>
# 子组件 Child.vue
<template>
<div>
<!-- 显示从父组件接收到的数据 -->
<p>{{ message }}</p>
<!-- 点击按钮触发向父组件发送事件 -->
<button @click="sendEventToParent">向父组件发送事件</button>
</div>
</template>
<script>
import { defineComponent } from 'vue';
export default defineComponent({
// 声明接收父组件传递的 props
props: {
message: {
type: String,
required: true
}
},
// 声明可触发的自定义事件
emits: ['child-event'],
setup(props, { emit }) {
// 触发向父组件发送事件的方法
const sendEventToParent = () => {
// 触发自定义事件并传递数据给父组件
emit('child-event', '来自 Vue 3 子组件的数据');
};
// 返回需要在模板中使用的方法
return {
sendEventToParent
};
}
});
</script>
3. Vue2&3 keep-alive 組件
keep-alive
是 Vue 提供的一个内置组件,用于缓存动态组件或路由组件,避免组件在切换时重复创建和销毁,从而提高组件的性能和响应速度。下面分别介绍 Vue 2 和 Vue 3 中 keep-alive 的使用方法
activated
和deactivated
是比較特殊的兩個鉤子,需要keep-live
配合使用
當引入keep-alive
的時候,頁面第一次進入,鉤子的觸發順序created
=>mounted
=>activated
,退出時觸發deactivated
當再次進入(前進或後退)時,只觸發activated
核心功能相同:在
Vue 2
和Vue 3
中,keep-alive
组件的核心功能都是缓存组件实例,避免重复创建和销毁
基本用法相同:都是通过将需要缓存的组件包裹在<keep-alive>
标签内来实现缓存
Vue2 keep-alive
<template>
<!-- 使用 keep-alive 包裹需要缓存的组件 -->
<keep-alive>
<!-- 通过 is 指令动态切换组件 -->
<component :is="currentComponent"></component>
</keep-alive>
<!-- 切换组件的按钮 -->
<button @click="toggleComponent">Toggle Component</button>
</template>
<script>
// 引入组件
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
data() {
return {
// 当前显示的组件
currentComponent: 'ComponentA'
};
},
components: {
ComponentA,
ComponentB
},
methods: {
toggleComponent() {
// 切换组件
this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA';
}
}
};
</script>
// ComponentA.vue
<template>
<div>
<h1>Component A</h1>
</div>
</template>
<script>
export default {
activated() {
// 组件被激活时触发
console.log('Component A activated');
},
deactivated() {
// 组件被停用时触发
console.log('Component A deactivated');
}
};
</script>
Vue3 keep-alive
<template>
<!-- 使用 keep-alive 包裹需要缓存的组件 -->
<keep-alive>
<!-- 通过 is 指令动态切换组件 -->
<component :is="currentComponent"></component>
</keep-alive>
<!-- 切换组件的按钮 -->
<button @click="toggleComponent">Toggle Component</button>
</template>
<script setup>
import { ref } from 'vue';
// 引入组件
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
// 定义当前显示的组件
const currentComponent = ref(ComponentA);
const toggleComponent = () => {
// 切换组件
currentComponent.value = currentComponent.value === ComponentA ? ComponentB : ComponentA;
};
</script>
// ComponentA.vue
<template>
<div>
<h1>Component A</h1>
</div>
</template>
<script setup>
import { onActivated, onDeactivated } from 'vue';
// 组件被激活时触发
onActivated(() => {
console.log('Component A activated');
});
// 组件被停用时触发
onDeactivated(() => {
console.log('Component A deactivated');
});
</script>
進階性
爲什麽POST請求有時會重複調用兩次
網路問題
有時瀏覽器為了確保請求的可靠性,會在網路不穩定的情況下自動重試請求
如果第一次POST
請求因網路問題而沒有成功,瀏覽器可能會自動再發一次請求
這種情況下,我們會看到兩次POST
請求
跨域請求與預檢請求
當我們進行跨網域請求時,尤其是使用
CORS(跨網域資源共用)
時,瀏覽器會在正式發送POST
請求之前發送OPTIONS
請求,這就是所謂的預檢請求
這是為了確定伺服器是否允許跨網域請求
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
# 在開發者工具中,我們可以看到先發了一個OPTIONS請求,接著才是實際的POST請求
JS原型、原型鏈
原型
- ① 所有引用类型都有一个
__proto__ (隐式原型)
属性,属性值是一个普通的对象 - ② 所有函数都有一个
prototype(原型)
属性,属性值是一个普通的对象 - ③ 所有引用类型的
__proto__
属性指向它构造函数的prototype
原型鏈
当访问一个对象的某个属性时,会先在这个对象本身属性上查找,如果没有找到,则会去它的 __proto__
隐式原型上查找,即它的构造函数的 prototype
,如果还没有找到就会再在构造函数的 prototype
的 __proto__
中查找,这样一层一层向上查找就会形成一个链式结构,我们称为原型链
原型鏈判斷
Object.prototype.__proto__; //null
Function.prototype.__proto__; //Object.prototype
Object.__proto__; //Function.prototype
Object instanceof Function; //true
Function instanceof Object; //true
Function.prototype === Function.__proto__; //true
繼承 有哪些繼承 優點是什麼
继承(inheritance
)是面向对象软件技术当中的一个概念。如果一个类别 B
“继承自”另一个类别 A
,就把这个 B
称为“A
的子类”,而把 A
称为“B
的父类别”也可以称“A
是 B
的超类”.
组合继承: 原型链继承和借用构造函数方法组合就是组合继承。用原型链实现对原型属性和方法的继承,用借用构造函数技术来实现实例属性的继承.
寄生组合式继承: 结合借用构造函数传递参数和寄生模式实现继承。这是最成熟的方法,也是现在库实现的方法
優點:继承可以使得子类具有父类别的各种属性和方法,在子类别继承父类别的同时,可以重新定义某些属性,并重写某些方法,即覆盖父类别的原有属性和方法,使其获得与父类别不同的功能
new 操作符具体干了什么
- 新建一个空对象
obj
- 把
obj
的隐式原型和构造函数通过原型链连接起来 - 将构造函数的
this
指向obj
- 如果该函数没有返回对象,则返回
this
// 定义一个构造函数 Person,用于创建表示人的对象
// 构造函数通常首字母大写,这是一种约定俗成的写法,用于区分普通函数
// 参数 name 表示人的姓名,参数 age 表示人的年龄
function Person(name, age) {
// 将传入的 name 参数赋值给新对象的 name 属性
this.name = name;
// 将传入的 age 参数赋值给新对象的 age 属性
this.age = age;
}
// 自定义的函数 myNew,用于模拟 new 操作符的功能
// 参数 constructor 是一个构造函数,也就是我们想要用来创建对象的函数
// 使用剩余参数语法 ...args 接收传递给构造函数的所有参数,这些参数会在构造函数执行时使用
function myNew(constructor, ...args) {
// 步骤 1: 创建一个新对象
// Object.create(constructor.prototype) 方法用于创建一个新对象,
// 并将这个新对象的原型设置为构造函数的原型。
// 这样新对象就可以继承构造函数原型上定义的所有属性和方法
const newObj = Object.create(constructor.prototype);
// 步骤 2: 将新对象的 this 指向构造函数,并执行构造函数
// constructor.apply(newObj, args) 方法调用构造函数,
// 并将构造函数内部的 this 指向新创建的对象 newObj,
// 同时将之前收集的参数 args 传递给构造函数,让构造函数可以根据这些参数初始化新对象的属性
const result = constructor.apply(newObj, args);
// 步骤 3: 判断构造函数的返回值
// 如果构造函数返回的是一个对象(通过 typeof result === 'object' 判断类型为对象,
// 并且 result!== null 排除返回值为 null 的情况,因为 typeof null 也会返回 'object'),
// 就返回构造函数的返回值;
// 否则,返回我们在步骤 1 中创建的新对象 newObj
return typeof result === 'object' && result!== null? result : newObj;
}
// 使用自定义的 myNew 函数创建对象
// 这里将 Person 构造函数作为第一个参数传递给 myNew,
// 并将 'John' 和 30 作为后续参数传递,这些参数会在 Person 构造函数执行时使用
const person = myNew(Person, 'John', 30);
// 打印创建的对象
// 此时打印出的对象应该包含 name 和 age 属性,值分别为 'John' 和 30
console.log(person);
- Object.create(constructor.prototype):这行代码创建了一个新对象
newObj
,并将其原型指向构造函数的原型,这样,新对象就可以继承构造函数原型上的属性和方法 - constructor.apply(newObj, args):使用
apply
方法将构造函数的this
指向新对象newObj
,并执行构造函数,将参数args
传递给构造函数 - 返回值判断:如果构造函数返回一个对象,则返回该对象;否则,返回新创建的对象
newObj
js 有哪些方法改变 this 指向
call
,apply
,bind
三者的第一个参数都是 this
需要指向的对象,但在后续的参数上只有 apply
是接收一个数组,call
和 bind
用逗号分开;call
和 apply
直接调用,返回的是一个值,而 bind
不直接调用,返回的是一个函数形式,执行:foo.bind(obj)()
# call()
# call() 方法允许你调用一个函数,同时指定该函数内部 this 的值,并且可以依次传递参数给函数
// 定义一个对象,后续将作为 this 的指向
const person = {
name: 'Alice'
};
// 定义一个函数,函数内部使用 this 来访问属性
function introduce(hobby) {
// 打印出根据 this 指向的对象属性生成的介绍语句
console.log(`大家好,我叫 ${this.name},我喜欢 ${hobby}。`);
}
// 使用 call 方法调用 introduce 函数,并将 person 对象作为 this 的指向
// 同时传递 '画画' 作为 introduce 函数的参数
introduce.call(person, '画画');
# -------------------------------分割線-------------------------------------
# apply()
# apply() 方法和 call() 方法类似,同样用于调用函数并指定 this 的值,不同之处在于它接受一个数组作为函数的参数
// 定义一个对象,作为 this 的指向
const anotherPerson = {
name: 'Bob'
};
// 定义一个函数,内部使用 this 访问属性
function introduceFood(food1, food2) {
// 打印出根据 this 指向的对象属性生成的喜欢食物的语句
console.log(`我叫 ${this.name},我喜欢吃 ${food1} 和 ${food2}。`);
}
// 使用 apply 方法调用 introduceFood 函数
// 将 anotherPerson 对象作为 this 的指向
// 并以数组形式传递 '披萨' 和 '汉堡' 作为函数参数
introduceFood.apply(anotherPerson, ['披萨', '汉堡']);
# -------------------------------分割線-------------------------------------
# bind()
# bind() 方法会创建一个新的函数,在调用时会将 this 的值设置为你提供的值,并且可以预先传入部分参数
// 定义一个对象,作为 this 的指向
const student = {
name: 'Charlie'
};
// 定义一个函数,内部使用 this 访问属性
function study(subject) {
// 打印出根据 this 指向的对象属性生成的学习语句
console.log(`${this.name} 正在学习 ${subject}。`);
}
// 使用 bind 方法创建一个新的函数 newStudy
// 将 student 对象作为新函数内部 this 的指向
// 并预先传入 '数学' 作为参数
const newStudy = study.bind(student, '数学');
// 调用新函数
newStudy();
对一个函数链式调用 bind,this 指向的是谁?为什么?
在 JavaScript
中,对一个函数链式调用 bind
时,this
最终指向的是第一次调用 bind
时所指定的对象
- 原因
bind
方法会创建一个新的函数,在调用时这个新函数的this
值会被锁定为bind
方法调用时第一个参数所指定的对象
当对一个函数多次链式调用bind
时,后续的bind
调用并不会改变第一次bind
所确定的this
指向,因为后续的bind
是基于前一次bind
所创建的新函数来操作的,而前一次bind
已经固定了this
的指向
// 定义一个简单的函数,函数内部打印 this 的值
function printThis() {
console.log(this);
}
// 创建一个对象,后续会将其作为 this 指向
const obj1 = { name: 'obj1' };
const obj2 = { name: 'obj2' };
// 第一次调用 bind,将 this 指向 obj1
const bound1 = printThis.bind(obj1);
// 对 bound1 再次调用 bind,尝试将 this 指向 obj2
const bound2 = bound1.bind(obj2);
// 调用最终绑定后的函数
bound2();