vue3 articles

1. Create a vue3 project

  1. Created using vue-cli scaffolding
    • Installing vue-cli requires that the scaffolding version must be greater than 4.5
      • yarn global add @vue/cli
      • npm install -g @vue/cli
    • Create a vue3 project: vue create my-project
  2. 使用vite安装并指定模板
    • npm create vite@latest my-vue-app --template vue
    • yarn create vite my-vue-app --template vue
  3. 直接安装(默认基于vite构建),根据提示安装需要的依赖
    • npm init vue@latest
  4. Method 3 is recommended.
  5. The specific installation method can refer to

2. Life cycle

  1. 创建前:beforeCreate -> 使用setup()
  2. 创建后:created -> 使用setup()
  3. 挂载前:beforeMount -> onBeforeMount
  4. 挂载后:mounted -> onMounted
  5. Before Update: beforeUpdate -> onBeforeUpdate
  6. After update: updated -> onUpdated
  7. Before destruction: beforeDestroy -> onBeforeUnmount
  8. After destruction: destroyed -> onUnmounted
  9. Exception capture: errorCaptured -> onErrorCaptured
  10. Activated: onActivated is included in the component, there will be two more life cycle hook functions. Executed when activated.
  11. Switch: onDeactivated For example, switch from A component to B component, and execute when A component disappears

3. Combined API and optional API

  1. options Api is used in vue2. Write each function under the corresponding Api.当逻辑复杂的时候这种写法不利于代码阅读和代码维护。
  2. The composition API is used in vue3. Write each function independently and completely in setup(){},有利于代码阅读和维护

4.ref Responsive Data

  1. effect:定义一个响应式数据
  2. Syntax: const xxx = ref<data type: string|number> = (1)
  3. Operation: xxx.value
  4. use:在模板中不需要使用.value 可以直接使用
  5. Note: You can define basic data types or complex data types such as objects
    • Basic data type: The principle of responsiveness is still to do data hijacking and data update through get() and set() of Object.definedProperty().
    • Complex data types: internal help reactive is implemented through Proxy proxy

Five. reactive response data

  1. effect:定义一个复杂类型的响应式数据,例如对象
  2. Syntax: const xxx = reactive<data type> = ({})
  3. operate:直接读取不需要.value
  4. Remarks: The operation of the source object data through the Proxy proxy object is deep

6. Responsive principle

  1. Vue2 implements the data hijacking, combination and publishing subscriber mode through the get() and set() of Object.definedProperty().
  2. Vue3 is implemented by proxy
  3. Advantages of proxy :不需要像Object.definedProperty()的那样遍历每一个属性,有一定的性能提升
    proxy可以理解为在目标对象之前架设一层“拦截”,外界对该对象的访问都必须通过这一层拦截。这个拦截可以对外界的访问进行过滤和改写。
  4. When there are too many properties, use Object.definedProperty() to monitor each property by traversing. Using proxy does not require traversal, and will automatically monitor all attributes, which is conducive to performance improvement

Seven. Watch monitoring

  1. Listen to a ref attribute:
watch(a,(newValue,oldValue)=>{
    
    },immediate:true,deep:true) // 得到的newValue和oldValue是一个值

insert image description here

  1. Listen to multiple ref attributes:
watch([a,b,c,...],(newValue,oldValue)=>{
    
    },immediate:true,deep:true)  // 得到的newValue和oldValue是一个数组

insert image description here

  1. Listen to a property in a reactive:
watch(()=>a.name,(newValue,oldValue)=>{
    
    })

insert image description here

  1. Listen to some properties in a reactive:
watch([()=>a.name,()=>a.age],(newValue,oldValue)=>{
    
    })

insert image description here

  1. Listen to all attributes in a reactive:
watch(a,(newValue,oldValue)=>{
    
    })
// 无法获取oldValue
// 强制开启了深度监听(deep配置无效)

insert image description here

  1. Listen to ref and reactive data at the same time:
watch([a,()=>a.age],(newValue,oldValue)=>{
    
    })

insert image description here

  1. Special case:
watch(()=>a.job,(newValue,oldValue)=>{
    
    },deep:true)  
// job是一个复杂对象必须开启深度监听,无法获取oldValue
// 如果直接监听一个对象不需要开启深度监听
// 如果是用箭头函数形式则必须开启

insert image description hereinsert image description here
insert image description here

Eight. watchEffect monitoring

  1. Explanation: No need to specify which attribute, which attribute is used in the function body, is which attribute is monitored.
  2. The difference between watch
    • No need to manually import dependencies
    • Execute immediately, and a callback function will be executed every time it is initialized to automatically obtain dependencies
    • The original value cannot be obtained, only the changed value can be obtained
  3. Syntax: watchEffect((newValue)=>{})
    insert image description here
watchEffect(() => {
    
    
  userInfo.value = user.name + user.more.age;  // 可以看到上图中watchEffect实现了对name和age的监听
});

Nine. toRef and toRefs

  1. Function: It can be used to copy the attributes in reactive and then convert them into ref, which not only retains the responsiveness but also the reference. That is, after you modify the attribute copied from reactive, in addition to the view will be updated, the corresponding value in the original ractive will also be updated accordingly.
  2. toRef: copy the attributes in reactive 单个and convert them to ref
  3. toRefs: copy the attributes in reactive 所有and convert them to ref
  4. use
// toRef的使用
<template>
	// toRef的使用
	<h1>{
    
    {
    
    username}}</h1>
	// toRef的使用
	<h1>{
    
    {
    
    age}}</h1>
</template>
<script setup>
  	import {
    
    reactive,toRef,toRefs} from 'vue'
	const info = reactive({
    
    
		name:'wangjiajia',
		age:'25'
	})
	// toRef的使用
	const username = toRef(info,'name')

	// toRefs的使用
	const {
    
    name,age} = toRefs(info)
</script>
  1. Summarize
    • 使用toRef()解构出来的是对象中的某一个属性,可以在template中直接使用不用加.value。
    • 使用toRefs()是将整个对象解构,必须加上...,这样在template中就可以直接使用不用加.value。

10. shallowReactive and shallowRef

  1. effect:做数据响应式性能优化的
  2. shallowReactive:只处理对象最外层的响应(浅层响应)
  3. shallowRef:只处理基本数据类型的响应式, 不进行对象的响应式处理。
  4. Conditions of Use:
    • 如果有一个对象类型数据,结构比较深,但变化时只是外层属性变化使用shallowReactive。
    • 如果有一个对象类型数据,不希望他是响应式,使用shallowRef
  5. For example:
// shallowReactive的使用
const userInfo = shallowReactive({
    
       // 只将第一层数据做了响应式处理 
	name:'wangjiajia',
	age:25,
	like:{
    
    
		food:{
    
    
			apple:'橙子'    // 深层次的数据将会是一个普通的对象
		}
	}
})

// shallowRef的使用
const userInfo = shallowRef({
    
       // userInfo将不在是一个响应式对象
	name:'wangjiajia'
}) 

Eleven. readonly and shallowReadonly

  • readonly:让一个响应式数据变为只读的。(深层次)
  • shallowReadonly:让一个响应式数据变为只读的。(浅层次)
  • Application scenario: do not want the data to be modified
let person=reactive({
    
    
    name:'张三',
    age:18,
    job:{
    
    
        j1:{
    
    
            salary:20
		}
	}
})
person = readonly(person)   // person里面的所有属性都不可以被修改
person = shallowReadonly(person)   // person里面只有第一层属性不可以被修改

12. toRaw and markRaw

  1. toRaw:
    • effect:将一个reactive生成的响应式数据转为普通对象
    • scenes to be used:用于读取响应式对象对应的普通对象,对这个普通对象的所有操作不会引起页面更新
  2. markRaw:
    • 标记一个对象使其永远不会成为响应式
    • Application scenario:
      • Some values ​​should not be made responsive. For example, some complex third-party libraries
      • Skip reactivity can improve performance when rendering large lists with immutable data sources
  3. The difference between markRaw and readonly
    • markRaw标记一个对象使其永远不会成为响应式
    • readonly禁止对值得修改,响应式本身还存在。

13. Judgment of responsive data

  1. isRef(): Checks if a value is a ref object, returns true/false
  2. isReactive: Check whether an object is a reactive object, return true/false
  3. isReadonly: checks whether an object is a read-only property created by readonly
  4. isProxy: checks whether an object is a proxy object

Fourteen. provide and inject

Focus on the communication between components

15. vue3 routing jump (programmatic and declarative)

  1. Declarative:<router-link :to="{name:'',query:{}}">
  2. Programmatic:
    import { useRouter } from 'vue-router';
    const router = useRouter();
    • Without parameters:
      • router.push(‘/home’)
      • router.push({name:‘home’})
      • router.push({path:‘/home’})
    • With parameters ---- query parameters
      • router.push(name:‘home’,query:{id:1})
      • router.push(path:‘/home’,query:{id:1})
    • With parameters ---- params pass parameters
      • router.push(name:‘home’,params:{id:1})
    • Note: You can use either name or path to pass parameters in query. The parameters will be spliced ​​after the jump. Only name can be used to pass parameters in params, and parameters will not be spliced ​​after jumping. So query parameter passing is not as safe as params parameter passing.
    • Use this.$router.push for vue2 routing jump, and the rest of the parameters are the same as vue3

Sixteen. What are the main aspects of vue3 performance improvement?

  1. responsive system
  2. Source code volume: By adding tree sharking to the source code, the packaged volume of the project becomes smaller. Modules are loaded on demand
  3. Compile phase
    • The diff algorithm is different, vue2 traverses every DOM node. Vue3 is to mark each node first, and only traverse the nodes with marked changes
    • Static promotion: In vue3, elements that do not participate in the update will be statically promoted, which will only be created once and used directly next time without re-rendering
    • Open event listener cache
    • SSR (server rendering) optimization, when the static content is large enough, a static node will be generated. These static nodes will be directly innerHtml, so there is no need to create an object, and then render according to the object

Seventeen. Design goals of vue3

  1. Smaller: on-demand loading, with a smaller package size
  2. Faster: diff algorithm, static improvement, enable event monitoring cache, performance optimization
  3. More friendly: the source code is maintained through monorepo (a micro front-end technology that integrates code)
    • composition Apimonorepo
    • better ts support

18. Setup in vue3

Nineteen. The life cycle order of parent components and child components

  1. Compared with the external life cycle function, the execution life cycle in the setup will first point to the life cycle function in the setup, and then execute the external life cycle function.
  2. The overall sequence is as follows:
    • father setup
    • father onBeforeMount
    • child setup
    • Child onBeforeMount
    • 子onMounted
    • 父onMounted
    • father onBeforeUpdate
    • child onBeforeUpdate
    • 子onUpdated
    • 父onUpdated
      insert image description here
      insert image description here
      insert image description here

20. The component communication method of vue3

  • props / emit
  • v-model
  • provide/inject
  • refs
  • eventBus
  • vuex/pinia
  1. props / emit
    insert image description here
    insert image description here
    insert image description here
    insert image description here
    insert image description here

  2. v-model:双向绑定,props + emit('update:xxx',xxx)
    insert image description here
    insert image description hereinsert image description here
    insert image description here

  3. provide/inject

    • It is a pair of APIs provided in Vue.
    • 无论层级多深,API 都可以实现父组件到子孙组件的数据传递。
    • Can only be used to pass values ​​from parent components to descendant components.
    • When using provide for data transmission, try to use readonly to encapsulate data to prevent child components from modifying the data passed by the parent component.
    • 使用provide传过去的值一定要是proxy进行过代理的或者计算属性
      • For example:provide('listData', computed(() => state.listData))
      • provide('listData', toRef(state.listData))
        insert image description here
        insert image description here
  4. ref:ref + defineExpose({})
    insert image description here
    insert image description here

  5. eventBus:Vue 3 中移除了 eventBus,但可以借助第三方工具来完成。Vue 官方推荐使用 mitt 或 tiny-emitter,在大多数情况下,不建议使用全局事件总线来实现组件通信。虽然比较简单粗暴,但是维护事件总线从长远来看是个大问题,这里就不解释了。
    insert image description here

insert image description here
insert image description here
insert image description here

insert image description here
6. vuex / pinia:全局数据共享

Guess you like

Origin blog.csdn.net/du_aitiantian/article/details/128846763