您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

【整理总结】详解Vue3的11个知识点

2024/3/28 22:23:46发布4次查看
本篇文章总结分享vue3学习笔记,深入了解vue3的11个知识点,希望对大家有所帮助!
《vue3+node+webpack+api 商城项目工程化实战开发课!》
一、为什么选择compositionapivue2的局限性组件逻辑膨胀导致的可读性变差无法跨组件重用代码vue2对ts的支持有限在传统的optionsapi中我们需要将逻辑分散到以下六个部分。【相关推荐:vue.js视频教程】
optionsapi
componentspropsdatacomputedmethodslifecycle methods如何使用compositionapi解决问题最佳的解决方法是将逻辑聚合就可以很好的代码可读性。
这就是我们的compositionapi语法能够实现的功能。compositionapi是一个完全可选的语法与原来的optionapi并没有冲突之处。他可以让我们将相同功能的代码组织在一起,而不需要散落到optionsapi的各个角落
代码重用方法pkvue2中的跨组件重用代码,我们大概会有四个选择
1、mixin - 混入
代码混入其实就是设计模式中的混合模式,缺点也非常明显。可以理解为多重继承,简单的说就是一个人如何有两个父亲缺点
无法避免属性名冲突继承关系不清晰2、mixin factory - 混入工厂
返回一个
✅代码重用方便
✅继承关系清洗
3、scopeslots - 作用域插槽
❌可读性不高
❌配置复杂 - 需要再模板中进行配置
❌性能低 - 每个插槽相当于一个实例
4、compositionapi - 复合api
✅代码量少
✅没有引入新的语法,只是单纯函数
✅异常灵活
✅工具语法提示友好 - 因为是单纯函数所以 很容易实现语法提示、自动补偿
二、setup & ref使用compositionapi理由✅更好的typescript支持
✅在复杂功能组件中可以实现根据特性组织代码 - 代码内聚性, 比如:
排序和搜索逻辑内聚
✅组件间代码复用
setup是什么在以下方法前执行:componentspropsdatamethodscomputed propertieslifecycle methods可以不在使用难于理解的this有两个可选参数props - 属性 (响应式对象 且 可以监听(watch))import {watch} from "vue"export defalut { props: { name: string }, setup(props) { watch(() => { console.log(props.name) }) }}
context 上下文对象 - 用于代替以前的this方法可以访问的属性setup (props,context) { const {attrs,slots,parent,root,emit} = context}
ref是什么对基本数据类型数据进行装箱操作使得成为一个响应式对象,可以跟踪数据变化。
总结
可维护性明显提高
可以控制哪些变量暴露可以跟中哪些属性被定义 (属性继承与引用透明)三、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>attending</h2><ul>> <li v-for="(name,index) in event.attending" :key="index"> {{name}} </li></ul><button @click="increasecapacity()"> increase capacity</button>
在这里我们使用对象都是.属性的方式,但是如果 这个结构变化了,event分开了编程了一个个片段,这个时候就不能用.属性的方式了
//在这里可以使用torefsimport {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>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 - 生命周期钩子vue2vue3
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 :truerejected : falseresolved: falseerror : 返回执行错误
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 v-if="error">uh oh .. {{ error }}</div> <suspense> <template #default> <div> <event /> <asyncevent /> </div> </template> <template #fallback> 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 to="#end-of-body" :disabled="!showtext"> <!-- 【teleport : this should be at the end 】 --> <div> <video src="../assets/flower.webm" muted controls="controls" autoplay="autoplay" loop="loop"> </video> </div> </teleport> <div>【teleport : this should be at the top】</div> <button @click="showtext = !showtext">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>
更多编程相关知识,请访问:编程入门!!
以上就是【整理总结】详解vue3的11个知识点的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录