


[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3
This article summarizes and shares Vue3 study notes, and provides an in-depth understanding of 11 knowledge points of Vue3. I hope it will be helpful to everyone!
《Vue3 Node Webpack API Mall Project Engineering Practical Development Course! 》
1. Why choose CompositionAPI
Limitations of Vue2
- Poor readability caused by component logic expansion
- Unable to reuse code across components
- Vue2 has limited support for TS
In the traditional OptionsAPI we need to spread the logic into the following six parts. [Related recommendations: vue.js video tutorial]
OptionsAPI
- ##components
- props
- data
- computed
- methods
- lifecycle methods
This is what our CompositionAPI syntax can achieve. CompositionAPI is a completely optional syntax and has no conflict with the original OptionAPI. It allows us to organize code with the same function together without scattering it to every corner of the optionsAPICode reuse method PKCross-component reuse code in Vue2, we There are probably four options1. Mixin - Mixin
- Code mixing is actually the mixing mode in the design mode, and its shortcomings are also very obvious .
- Can be understood as multiple inheritance. Simply put, it is how a person has two fathers
Disadvantages
- Cannot be avoided Attribute name conflict
- Unclear inheritance relationship
2. setup & ref
Reason for using CompositionAPI
✅Better Typescript support✅In complex functional components, code can be organized according to characteristics - code cohesion, such as:Sort and search logic cohesion
What is setup
- Execute before the following method:
-
- Components
- Props
- Data
- Methods
- Computed Properties
- Lifecycle methods
- has two optional parameters
- props - properties (responsive object and can be monitored (watch))
import {watch} from "vue" export defalut { props: { name: String }, setup(props) { watch(() => { console.log(props.name) }) } }
setup (props,context) { const {attrs,slots,parent,root,emit} = context }
What is ref
The boxing operation of basic data type data makes it a responsive object that can track data changes.Summary
The maintainability is significantly improved
- 可以控制哪些变量暴露
- 可以跟中哪些属性被定义 (属性继承与引用透明)
三、Methods
基础用法
自动拆装箱总结
- JS :需要通过.value访问包装对象
- 模板: 自动拆箱
四、 Computed - 计算属性
这个地方实在没什么好讲的,和Vue2没变化
<template> <div> <div>Capacity: {{ capacity }}</div> <p>Spases Left: {{ sapcesLeft }} out of {{ capacity }}</p> <button @click="increaseCapacity()">Increase Capacity</button> </div> </template> <script> import { ref, computed, watch } from "vue"; export default { setup(props, context) { const capacity = ref(3); const attending = ref(["Tim", "Bob", "Joe"]); function increaseCapacity() { capacity.value++; } const sapcesLeft = computed(() => { return capacity.value - attending.value.length; }); return { capacity, increaseCapacity, attending, sapcesLeft }; }, }; </script>
五、Reactive - 响应式语法
之前reactive 的 Ref 去声明所有的响应式属性
import { ref,computed } from 'vue' export default { setup(){ const capacity = ref(4); const attending = ref(["Tim","Bob","Joe"]); const spacesLeft = computed(()=>{ return capacity.value - attending.value.length }) function increaseCapacity(){ capacity.value ++;} return { capacity,increaseCapacity,attending,spacesLeft} } }
但是有另一个等效的方法用它去代替 reactive 的Ref
import { reactive,computed } from 'vue' export default { setup(){ const event = reactive({ capacity:4, attending:["Tim","Bob","Joe"], spacesLeft:computed(()=>{ return event.capacity - event.attending.length; }) }) } }
过去我们用vue2.0的data来声明响应式对象,但是现在在这里每一个属性都是响应式的包括computed 计算属性
这2种方式相比于第一种没有使用.
接下来 我们再声明method 这2种语法都ok,取决于你选择哪一种
setup(){ const event = reactive(){ capacity:4, attending:["Tim","Bob","Joe"], spacesLeft:computed(()=>{ return event.capacity - event.attending.length; }) function increaseCapacity(){event.capacity++} //return整个对象 return {event,increaseCapacity} } }
<p>Spaces Left:{{event.spacesLeft}} out of {{event.capacity}}</p> <h2 id="Attending">Attending</h2> <ul>> <li v-for="(name,index) in event.attending" :key="index"> {{name}} </li> </ul> <button @click="increaseCapacity()"> Increase Capacity</button>
在这里我们使用对象都是.属性的方式,但是如果 这个结构变化了,event分开了编程了一个个片段,这个时候就不能用.属性的方式了
//在这里可以使用toRefs import {reactive,computed,toRefs} from 'vue' export default{ setup(){ const event = reactive({ capacity:4, attending:["Tim","Bob","Joe"], spacesLeft:computed(()=>{ return event.capacity -event.attending.length; }) }) function increaseCapacity(){ event.capacity ++ } return {...toRefs(event),increaseCapacity} } }
如果没有 increaseCapacity() 这个方法 直接可以简化为
return toRefs(event)
完整代码
<div> <p>Space Left : {{event.spacesLeft}} out of {{event.capacity}} </p> <h2 id="Attending">Attending</h2> <ul> <li v-for="(name,index)" in event.attending :key="index">{{name}} </li> </ul> <button @click="increaseCapacity">Increase Capacity</button> </div> </template> <script> //第一种 import {ref,computed } from 'vue' export default { setup(){ const capacity = ref(4) const attending = ref(["Tim","Bob","Joe"]) const spaceLeft = computed(()=>{ return capacity.value - attending.value.length; }); function increaseCapacity(){ capacity.value++; } return {capacity,increaseCapacity,attending,spaceLeft} } } //返回一个响应式函数 第二种 import { reactive,computed } from 'vue' export default { setup(){ const event = reactive({ capacity:4, attending:["Tim","Bob","Joe"], spaceLeft:computed(()=>{ return event.capacity - event.attending.length; }) }) //我们不再使用.value function increaseCapacity() { event.capacity++; } //把这个event放入到template中 return { event,increaseCapacity} } } </script>
六、 Modularizing
使用CompositionAPI的两个理由
1、可以按照功能组织代码
2、组件间功能代码复用
七、 LifecycleHooks - 生命周期钩子
Vue2 | Vue3 |
---|---|
beforeCreate | ❌setup(替代) |
created | ❌setup(替代) |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeDestroy | onBeforeUnmount |
destroyed | onUnmounted |
errorCaptured | onErrorCaptured |
- | ?onRenderTracked |
- | ?onRenderTriggered |
setup中调用生命周期钩子
import { onBeforeMount,onMounted } from "vue"; export default { setup() { onBeforeMount(() => { console.log('Before Mount!') }) onMounted(() => { console.log('Before Mount!') }) }, };
八、Watch - 监听器
// 所有依赖响应式对象监听 watchEffect(() => { results.value = getEventCount(searchInput.value); }); // 特定响应式对象监听 watch( searchInput, () => { console.log("watch searchInput:"); } ); // 特定响应式对象监听 可以获取新旧值 watch( searchInput, (newVal, oldVal) => { console.log("watch searchInput:", newVal, oldVal); }, ); // 多响应式对象监听 watch( [firstName,lastName], ([newFirst,newLast], [oldFirst,oldlast]) => { // ..... }, ); // 非懒加载方式监听 可以设置初始值 watch( searchInput, (newVal, oldVal) => { console.log("watch searchInput:", newVal, oldVal); }, { immediate: true, } );
九、Sharing State - 共享状态
编写一个公共函数usePromise函数需求如下:
- results : 返回Promise执行结果
- loading: 返回Promise运行状态
- PENDING :true
- REJECTED : false
- RESOLVED: false
- error : 返回执行错误
import { ref } from "vue"; export default function usePromise(fn) { const results = ref(null); // is PENDING const loading = ref(false); const error = ref(null); const createPromise = async (...args) => { loading.value = true; error.value = null; results.value = null; try { results.value = await fn(...args); } catch (err) { error.value = err; } finally { loading.value = false; } }; return { results, loading, error, createPromise }; }
应用
import { ref, watch } from "vue"; import usePromise from "./usePromise"; export default { setup() { const searchInput = ref(""); function getEventCount() { return new Promise((resolve) => { setTimeout(() => resolve(3), 1000); }); } const getEvents = usePromise((searchInput) => getEventCount()); watch(searchInput, () => { if (searchInput.value !== "") { getEvents.createPromise(searchInput); } else { getEvents.results.value = null; } }); return { searchInput, ...getEvents }; }, };
十、Suspense - 悬念
复杂的Loading实现
我们考虑一下当你加载一个远程数据时,如何显示loading状态
通常我们可以在模板中使用v-if
但是在一个组件树中,其中几个子组件需要远程加载数据,当加载完成前父组件希望处于Loading状态时我们就必须借助全局状态管理来管理这个Loading状态
Suspense基础语法
这个问题在Vue3中有一个全新的解决方法。
这就是Suspense Component,悬念组件。
<template> <div> <div>Uh oh .. {{ error }}</div> <suspense> <template> <div> <event></event> <asyncevent></asyncevent> </div> </template> <template> Loading.... </template> </suspense> </div> </template> <script> import { ref, onErrorCaptured, defineAsyncComponent } from "vue"; import Event from "./Event.vue"; const AsyncEvent = defineAsyncComponent(() => import("./Event.vue")); export default { components: { Event, AsyncEvent, }, setup() { const error = ref(null); onErrorCaptured((e) => { error.value = e; // 阻止错误继续冒泡 return true; }); return { error }; }, }; </script>
骨架屏实现
十一、Teleport - 传送门
功能
类似React中的Portal, 可以将特定的html模板传送到Dom的任何位置
基础语法
通过选择器QuerySelector配置
示例代码
<template> <div> <teleport> <!-- 【Teleport : This should be at the end 】 --> <div> <video> </video> </div> </teleport> <div>【Teleport : This should be at the top】</div> <button>Toggle showText</button> </div> </template> <script> import { ref } from "vue"; export default { setup() { const showText = ref(false); setInterval(() => { showText.value = !showText.value; }, 1000); return { showText }; }, }; </script>
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of [Compilation and summary] Detailed explanation of 11 knowledge points of Vue3. For more information, please follow other related articles on the PHP Chinese website!

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

Vue.js is suitable for fast development and small projects, while React is more suitable for large and complex projects. 1.Vue.js is simple and easy to learn, suitable for rapid development and small projects. 2.React is powerful and suitable for large and complex projects. 3. The progressive features of Vue.js are suitable for gradually introducing functions. 4. React's componentized and virtual DOM performs well when dealing with complex UI and data-intensive applications.

Vue.js and React each have their own advantages and disadvantages. When choosing, you need to comprehensively consider team skills, project size and performance requirements. 1) Vue.js is suitable for fast development and small projects, with a low learning curve, but deep nested objects can cause performance problems. 2) React is suitable for large and complex applications, with a rich ecosystem, but frequent updates may lead to performance bottlenecks.

Vue.js is suitable for small to medium-sized projects, while React is suitable for large projects and complex application scenarios. 1) Vue.js is easy to use and is suitable for rapid prototyping and small applications. 2) React has more advantages in handling complex state management and performance optimization, and is suitable for large projects.

Vue.js and React each have their own advantages: Vue.js is suitable for small applications and rapid development, while React is suitable for large applications and complex state management. 1.Vue.js realizes automatic update through a responsive system, suitable for small applications. 2.React uses virtual DOM and diff algorithms, which are suitable for large and complex applications. When selecting a framework, you need to consider project requirements and team technology stack.

Vue.js and React each have their own advantages, and the choice should be based on project requirements and team technology stack. 1. Vue.js is community-friendly, providing rich learning resources, and the ecosystem includes official tools such as VueRouter, which are supported by the official team and the community. 2. The React community is biased towards enterprise applications, with a strong ecosystem, and supports provided by Facebook and its community, and has frequent updates.

Netflix uses React to enhance user experience. 1) React's componentized features help Netflix split complex UI into manageable modules. 2) Virtual DOM optimizes UI updates and improves performance. 3) Combining Redux and GraphQL, Netflix efficiently manages application status and data flow.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version
