Vue3优势、VsCode插件、理解setup, watch, toRef等细节点
再学Vue3
必要性
Vue3性能大幅提升(因为使用proxy代理后,不需要递归劫持)
Vue3 支持 tree shaking,可以进行按需编译,编译后的文件体积比Vue2更小
更支持 Typescript,有助于大型项目开发
更先进的功能,比如:teleport,suspense等
代码聚合
使用Vite
创建应用指令:
npm init vite-app xxx复制代码
本质上就是在执行
npx create-vite-app xxx复制代码
但是,vite最新创建指令是:(最好用下面的新创建方式)
npm init vite xxx复制代码
npx
是指临时下载 create-vite-app
包,帮我们创建项目,然后自动删除
npm
要求项目命名不可以有大驼峰,可以用 -
VS Code 插件
Volar:Vue3语法支持
Vue.js AutoImport:引用组件
Vue3 Snippets:Vue3代码片段
Prettier-Code formatter:代码格式化
ESLint:代码质量检查
EditorConfig for VS Code:覆盖编辑器编码风格配置
入口函数 setup
返回的对象,被挂载到了 Vue实例对象上,所以才可以在模板中使用
API
computed 计算属性
作用:基于现有状态,生成另外的状态
watch 监听
A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.
监听的资源,必须是一个 getter/effect 函数(遇到基本类型时使用getter)、一个ref、一个reactive对象(一个Proxy对象即可),或者这些类型组合的数组。
getter 函数
const num = ref(1); // getter形式 watch( () => num.value, (newValue, oldValue) => { console.log(newValue, oldValue); } );复制代码
ref
const num = ref(1); // watch监听单个资源 watch(num, (newValue, oldValue) => { console.log(newValue, oldValue); });复制代码
reactive对象
const person = reactive({ name: "frank" }); // watch监听单个资源 watch(person, (newValue, oldValue) => { console.log(newValue, oldValue); });复制代码
以上组合成的数组
const man = ref({ age: 22 }); const person = reactive({ name: "frank" }); // watch监听单个资源 watch([() => man.value.age, person], (newValue, oldValue) => { console.log(newValue, oldValue); });复制代码
watchEffect
立即执行传入的函数,同时响应式追踪依赖,并在其依赖改变时,重新运行该函数
const count = ref(0) watchEffect(() => console.log(count.value))复制代码
toRef 函数
将原响应式数据内部的 某个属性
转为 新的ref
以供直接使用,简化数据层级
注意:
toRef 接受的第一个参数要是一个对象,转引用类型的 ref 需要
.value
setup(props) { const man = ref({ age: 22 }); const person = reactive({ name: "frank" }); return { // 转 引用类型 ref,要用.value 拿到对象 age: toRef(man.value, "age"), // 转 reative类型,直接用 reactive对象 name: toRef(person, "name"), }; },复制代码
toRefs 函数
批量数据转换,将对象里每个属性 转为ref
,可以用来直接解构赋值
const man = ref({ age: 22 }); const person = reactive({ name: "frank", gender: 0 }); const { age } = toRefs(man.value); const { gender, name } = toRefs(person);复制代码
获取props
注意:
必须在 props 属性中声明,
setup(props)
才可以拿到props
中属性在
setup
中拿到的props
不要直接解构赋值,会失去响应性,建议用toRefs
解构使用props: ["msg"], setup(props) { const { msg1 } = props; const { msg } = toRefs(props); // not OK watch( () => msg1, () => { console.log("直接解构"); } ); // OK watch(props, () => { console.log("props"); }); // OK watch( () => props.msg, () => { console.log("props.msg"); } ); // OK watch(msg, () => { console.log("msg"); }); }, };复制代码
\
作者:AA ????『東』????????
链接:https://juejin.cn/post/7028173762201649160