Home > Article > Web Front-end > Let’s talk about how Vue2 developers can quickly get started with Vue3
How to get started with Vue3 quickly? The following article will compare Vue2 and Vue3, and introduce how Vue2 developers can quickly get started with Vue3. I hope it will be helpful to everyone!
The author was a Vue2 React developer before. Since the project needs to be directly started with Vue3, I will learn it quickly and compare some differences related to React. Prerequisites for reading: Have already started the development of Vue2
, the main issues discussed in this article:
The new features of Vue3
Some differences between Vue2 and Vue3
How Vue2 developers can quickly get started with Vue3
vue video tutorial)
, and Vue3 template supports
multiple nodes, similar to react fragments
are basically in the script (Option api -> Composition api). You will no longer see this filling the screen! ! !
is The latest API of the browser is more powerful.
version
and cannot perfectly support
TypeScript (so the technology selection in the early stage of the project is very important)
, providing the same TS support as React
support, including
vitest, etc., the official provides more peripheral tools
Needless to say
, similar to the function bound by @click, no need to create multiple times, placed in the cacheHandler cache
: Vue 3.0 will directly convert static tags into text. Compared with React, it will first JSX is converted into virtual DOM, and then the virtual DOM is converted into HTML. Vue3 is much faster.
Give up the past mixins and use Hooks to solve some shortcomings of past mixins
I don’t know much about it, I will add more later
to optimize diff performance
=》and
the amount of dynamic content, which is a very big performance breakthrough. Lifting the code outside of the render function avoids re-creating these objects on every render, greatly improving memory usage and reducing the frequency of garbage collection.
vue.js, so that if the user wants to use the reactive style of vue3.0, they can
depend on reactive independently instead of relying on the entire vue.js, reducing the size of the reference package. But vue2.x cannot do this.
What is a composite API? - Vue official
setup
Options are executed before the component is created. Once props
is parsed, it will be used as the entry point to the composite API. await syntax
< ;script lang="ts" setup>
is enough, or you can use
<script> const result = await Http.get('/getUserInfo') </script> // or export default { setup(props, context) { // Attribute (非响应式对象,等同于 $attrs) console.log(context.attrs) // 插槽 (非响应式对象,等同于 $slots) console.log(context.slots) // 触发事件 (方法,等同于 $emit) console.log(context.emit) // 暴露公共 property (函数) console.log(context.expose) } }
basic type
.value
needs to be used in script to callhas a certain mental burden, especially It is also clearly stated that direct access in script will not be supported. The reason is that the basic type cannot intercept its changes. Of course, some people have proposed using syntax similar to new String('foo') to wrap the basic type. Personally, I feel that it would be good to directly use the supported reactive
Ref
ts definition import { type Ref } from 'vue';
isRef
Determine whether it is a ref object. Generally, variables created by ref, toRef, toRefstoRefs
Deconstruct the reactive object
into a single responsive objectshallowRef
Create a ref that tracks changes in its own .value, but does not make its value responsive. It is simply understood as creating a non-responsive variable with the same structure as reftriggerRef
Force update page DOM. Even if the created ref has not changed, if you want to update the dom, you can use customRef
to provide get and set similar to computed, and you can customize the ref behaviorreference type
proxy object
recursive by default. If the value of a certain layer is changed, it will be called recursively to re-render the dom.
directly, the responsiveness will be lost, and it needs to be wrapped with
toRefs. Directly changing the reference address of the reference type will also result in loss of responsiveness
Change the value of reactive It is read-only
It can only respond to shallow data. If it is deep data, it will only change the value but not the view
import { reactive, toRefs } from 'vue' const book = reactive({ author: 'Vue Team', year: '2020', title: 'Vue 3 Guide', description: 'You are reading this book right now ;)', price: 'free' }) let { author, title } = toRefs(book) title.value = 'Vue 3 Detailed Guide' // 我们需要使用 .value 作为标题,现在是 ref console.log(book.title) // 'Vue 3 Detailed Guide'
<script> import { onMounted } from 'vue'; const getUserInfo = () => { console.log('获取用户信息'); }; onMounted(getUserInfo); </script>
watch(() => articleInfo.author, (newVal) => {})
,第一个参数为箭头函数返回要监听的目标属性import { ref, reactive, watch } from 'vue' const counter1 = ref(0) const counter2 = ref(0) // 监听多个 watch([counter1, counter2], (newValue, oldValue) => { console.log('The new counter1 value is: ' + counter1.value) console.log('The new counter2 value is: ' + counter2.value) }) const obj = reactive({ name: 'JJ', age: 18 }) // 深度监听对象 watch(obj, (newValue, oldValue) => { console.log('The new obj value is: ' + obj.value) }, { deep: true, immediate: true }) // watch监听单个属性 watch(() => obj.name, (newValue, oldValue) => { console.log('The new obj value is: ' + obj.value) }, { deep: true, immediate: true })
响应式的属性
watchEffect
是拿不到的。显式
指定依赖源,watchEffect - 自动
收集依赖源可以理解为watchEffect 就是配置了{ immediate: true } 的watch
antfu小哥
:推荐在大部分时候用 watch 显式的指定依赖以避免不必要的重复触发,也避免在后续代码修改或重构时不小心引入新的依赖。watchEffect 适用于一些逻辑相对简单,依赖源和逻辑强相关的场景(或者懒惰的场景 )。const stopWatch = watchEffect( (oninvalidate): void => { oninvalidate(() => { console.log("前置校验函数"); }); // 引用了响应式的属性 count console.log("watchEffect count变化", count.value); }, { // 副作用刷新时机 flush 一般使用post // 可选:pre(组件更新前执行)/sync(强制效果始终同步触发)/post(组件更新后执行) flush: "post", // 开发调试 onTrigger() { console.log("开发调试"); }, } );
import { ref, computed } from 'vue' const counter = ref(0) const twiceTheCounter = computed(() => counter.value * 2) // get set写法 const plusOne = computed({ get: () => counter.value + 1, set: (val) => { counter.value = val - 1 }, }) plusOne.value = 1 console.log(counter.value) // 0 counter.value++ console.log(counter.value) // 1 console.log(twiceTheCounter.value) // 2
// template <suspense> <template> <asynccomponent></asynccomponent> </template> <template> <div>loading...</div> </template> </suspense> // script const AsyncComponent = defineAsyncComponent(() => import('./asyncComponent.vue'))
Teleport 是一种能够将我们的模板渲染至指定DOM节点,不受父级style、v-show等属性影响,但data、prop数据依旧能够共用的技术;类似于 React 的 Portal
。之前写react是不怎么用这个属性,vue3这个估计也没多大用。
主要解决的问题 因为Teleport节点挂载在其他指定的DOM节点下,完全不受父级style样式影响
to 属性 插入指定元素位置,body,html,自定义className等等
<teleport> <loading></loading> </teleport>
defineXxxx 无需import即可直接使用
和vue2一致
两者用法,除了pina没有Mutations,差别不大。但是官方推荐的东西,自然有它的各种优点
react中 {{}} => {}
import { ref } from 'vue' let v = ref<string>('') const renderDom = () => { return ( <input> <div> {v.value} </div> > ) } export default renderDom</string>
无需导入xxx,import { reactive,ref } from "vue";
,只需要用即可
自定义组件名称,需要引入插件unplugin-vue-define-options
,并在vite中配置
import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import DefineOptions from 'unplugin-vue-define-options/vite'; export default defineConfig({ plugins: [vue(), DefineOptions()], });
不使用插件,也可以通过多写一个script标签来单独写options
<script> export default { name: "TButton", }; </script> <script> defineOptions({ name: 'TButton', }); </script>
或者通过项目配置,指定相关插件配置
import { Directive } from "vue"; const vMove: Directive = { mounted(el: HTMLElement) { let moveEl = el.firstElementChild as HTMLElement; const mouseDown = (e: MouseEvent) => { //鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离 console.log(e.clientX, e.clientY, "-----起始", el.offsetLeft); let X = e.clientX - el.offsetLeft; let Y = e.clientY - el.offsetTop; const move = (e: MouseEvent) => { el.style.left = e.clientX - X + "px"; el.style.top = e.clientY - Y + "px"; console.log(e.clientX, e.clientY, "---改变"); }; document.addEventListener("mousemove", move); document.addEventListener("mouseup", () => { document.removeEventListener("mousemove", move); }); }; moveEl.addEventListener("mousedown", mouseDown); }, };
用了react hook的人都知道很香,vue3支持这个相当不错,能解决很多业务场景的封装
可以当做mixins写
// useWindowResize import { onMounted, onUnmounted, ref } from "vue"; function useWindowResize() { const width = ref(0); const height = ref(0); function onResize() { width.value = window.innerWidth; height.value = window.innerHeight; } onMounted(() => { window.addEventListener("resize", onResize); onResize(); }); onUnmounted(() => { window.removeEventListener("resize", onResize); }); return { width, height }; } export default useWindowResize;
Vue3 的依赖追踪是全自动的,不需要担心传了错误的依赖数组给 useEffect/useMemo/useCallback 从而导致回调中- 使用了过期的值
Vue3 Hook也没React Hook那么多限制,后续用用看怎么样
笔者vue3也刚用不久,如有错误,还请兄弟们指出
本文所有demo都在该仓库中JJ-UI 一款Vue3组件库,参考大佬文章刚刚搭建好,后续会基于这个架子开发自己的vue3组件库
The above is the detailed content of Let’s talk about how Vue2 developers can quickly get started with Vue3. For more information, please follow other related articles on the PHP Chinese website!