Vue3 tutorial to help you get started

catalogue

preface

These contents are recorded by the blogger during the learning process. Some unimportant points are skipped. If necessary, query the documents by yourself. In fact, the learning cost from V2 to V3 is not high. If you are familiar with V2, you can start V3 after reading this article.

Vue3 official website

Online source code compilation address

1,setup

Setup is the container of all composition APIs, and the value is a function. The data, methods, etc. used in the component should be configured in the setup, which will be executed once before beforeCreate. Note: in V3, this is no longer pointing to Vue instances, and accessing this will be undefined

1.1, return value

  • If an object is returned, the properties and methods in the object can be used directly in the template.
  • If you return a rendering function: you can customize the rendering content.

1.2 points for attention

Try not to mix with V2 configuration

Properties and methods in setup can be accessed in V2 configuration (data, methods, computed...).
However, the V2 configuration (data, methods, computed...) cannot be accessed in setup.
If there are duplicate names, setup takes precedence.

setup cannot be an async function

Because the return value is no longer the return object, but Promise, the template cannot see the attributes in the return object. (you can also return a Promise instance later, but you need the cooperation of suspend and asynchronous components)

1.3, syntax

<script>
import { ref, reactive } from 'vue'

export default {
	name: 'Home',
	setup(props, context) {
		const title = ref('title')
		const data = reactive({
			value: 'Ha ha ha'
		})
		return {
		  title,
		  data
		}
	}
}
</script>

1.4 parameters of setup

  • props: the value is an object, containing the attributes passed from outside the component and declared and received inside the component

  • Context: context object

    • Attrs: the value is an object and contains attributes passed from outside the component but not declared in the props configuration, which is equivalent to this.$attrs
    • Slots: received slot content, equivalent to this.$slots
    • Emit: a function that distributes custom events, equivalent to this.$emit

2. ref create responsive data

Using ref, you can create a reference object (ref object for short) containing responsive data, which can be either a basic type or an object.

grammar

// establish
const xxx = ref(value)

// use
xxx.value

// In template
<div>{{xxx}}</div>

3. Create reactive data

Define the responsive data of an object type. The internal Proxy implementation based on ES6 operates the internal data of the source object through the Proxy object

grammar

// establish
const xxx = reactive({
    xxx: ''
})

// use
xxx.xxx

4. Calculated calculation attribute

It is consistent with the function of computed configuration in V2

grammar

import { computed } from 'vue'

setup(){
	// Abbreviated grammar
    let fullName = computed(() => {
        return person.firstName + '-' + person.lastName
    })
    
    // Complete grammar
    let fullName = computed({
        get(){
            return person.firstName + '-' + person.lastName
        },
        set(value){
            const nameArr = value.split('-')
            person.firstName = nameArr[0]
            person.lastName = nameArr[1]
        }
    })
    
    return fullName
}

5. watch monitoring

It is consistent with the watch configuration function in V2, and the syntax is slightly changed

grammar

  • Scenario 1: monitor the responsive data defined by ref
watch(sum, (newValue, oldValue) => {
	console.log('sum Changed', newValue, oldValue)
}, {immediate:true})
  • Scenario 2: monitor the responsive data defined by multiple ref s
watch([sum, msg], (newValue,oldValue) => {
	console.log('sum or msg Changed', newValue,oldValue)
}) 
  • Scenario 3: monitor reactive defined responsive data
// If the watch monitors reactive defined responsive data, the oldValue cannot be obtained correctly
// If the watch monitors responsive data defined by reactive, the deep monitoring is forced on
watch(person, (newValue, oldValue) => {
	console.log('person Changed', newValue, oldValue)
}, { immediate:true, deep:false }) // The deep configuration here no longer works
  • Scenario 4: monitor an attribute in the responsive data defined by reactive
watch(() => person.job, (newValue, oldValue) => {
	console.log('person of job Changed', newValue, oldValue)
}, { immediate:true, deep:true }) 
  • Scenario 5: monitor some attributes in the reactive data defined by reactive
watch([() => person.job, () => person.name], (newValue, oldValue) => {
	console.log('person of job Changed', newValue, oldValue)
}, { immediate:true, deep:true })
  • Special case: the deep configuration is valid because it monitors an attribute in the object defined by the reactive element
watch(() => person.job, (newValue, oldValue) => {
    console.log('person of job Changed', newValue, oldValue)
}, { deep:true })

6. watchEffect listening callback

The difference between watch and watch is that watch should indicate both the monitored properties and the monitored callbacks. The watchEffect does not specify which attribute to monitor or which attribute to use in the monitored callback, so it monitors which attribute and does not need to write the return value.

grammar

// As long as the data used in the callback changes, the callback will be directly re executed
watchEffect(() => {
    const x1 = sum.value
    const x2 = person.age
    console.log('watchEffect The configured callback was executed')
})

7. Life cycle

The lifecycle is all written in setup

7.1, change

  • beforeDestroy renamed beforeUnmount
  • destroyed renamed unmounted
  • beforeCreate => setup
  • created => setup
  • beforeMount => onBeforeMount
  • mounted => onMounted
  • beforeUpdate => onBeforeUpdate
  • updated => onUpdated
  • beforeUnmount => onBeforeUnmount
  • unmounted => onUnmounted

7.2 grammar

setup() {
    onMounted(() => {
      console.log('mounted')
    })
}

8. toRef create ref

Create a ref object whose value value points to an attribute in another object

grammar

const state = reactive({
  foo: 1,
  bar: 2
})

const fooRef = toRef(state, 'foo')

// Pass props
export default {
  setup(props) {
    useSomeFeature(toRef(props, 'foo'))
  }
}

9. toRefs response conversion

Convert a responsive object into a normal object, where each property of the result object is a ref pointing to the corresponding property of the original object

grammar

const state = reactive({
  foo: 1,
  bar: 2
})

const stateAsRefs = toRefs(state)
// At this point, state and stateAsRefs are associated

10. shallowReactive responsive outer layer conversion

Only the response (shallow response) of the outermost attribute of the object is processed. Applicable to: an object data has a deep structure, but only the outer attributes change when it changes

grammar

const state = shallowReactive({
  foo: 1,
  nested: {
    bar: 2
  }
})

11. shallowRef basic data response

Only basic data type responses are processed, and object responses are not processed. Applicable to: for an object data, subsequent functions will not modify the attributes in the object, but generate a new object to replace it

grammar

const shallow = shallowRef({
  greet: 'Hello, world'
})

12. The readonly response becomes read-only

Make a responsive data read-only (deep read-only) and apply it when you don't want the data to be modified

grammar

const shallow = shallowRef({
  greet: 'Hello, world', // read-only
  nested: {
    bar: 2 // read-only
  }
})

13. The shallowReadonly response becomes read-only

Make a responsive data read-only (shallow read-only) and apply it when you don't want the data to be modified

grammar

const shallow = shallowReadonly({
  foo: 1, // read-only
  nested: {
    bar: 2 // Non read only
  }
})

14. toRaw response becomes non response

Turn a reactive object generated by reactive into an ordinary object. All operations on this ordinary object will not cause page updates.

grammar

const foo = {}
const Foo = reactive(foo)
console.log(toRaw(Foo) === foo) // true

15. The markRaw flag is never responsive

Mark an object so that it will never become a responsive object again. Some values should not be set to responsive, such as complex third-party class libraries. When rendering a large list with immutable data sources, skipping responsive conversion can improve performance.

grammar

const foo = markRaw({})
console.log(isReactive(reactive(foo))) // false

// It can also be used when nested in other responsive objects
const bar = reactive({ foo })
console.log(isReactive(bar.foo)) // false

16. customRef depends on update control

Create a custom ref and explicitly control its dependency tracking and update triggers. It requires a factory function that takes the track and trigger functions as arguments and should return an object with get and set.

grammar

<script>
import { customRef } from 'vue'

export default {
	name: 'Home',
	setup() {
	    // Implementation of anti shake function
		const fn = function(value, delay = 500) {
			let timeout
			return customRef((track, trigger) => {
				return {
					get() {
						track()
						return value
					},
					set(newValue) {
						clearInterval(timeout)
						timeout = setTimeout(() => {
							console.log(newValue)
							value = newValue
							trigger()
						}, delay)
					}
				}
			})
		}
		const keyword = fn('', 500)
		return {
			keyword
		}
	}
}
</script>

17. Provide & inject communication

To realize the communication between ancestor and descendant components, the parent component has a provide option to provide data, and the descendant component has an inject option to start using these data

grammar

// Ancestor component
setup(){
    let car = reactive({ name:'Benz', price:'40 ten thousand' })
    provide('car', car)
}

// Descendant component
setup(props, context){
    const car = inject('car')
    return { car }
}

18. Judgment of responsive data

18.1,isRef

Check whether a value is a ref object

grammar

const val = ref('xxx')
isRef(val) // true

18.2,isReactive

Check whether a value is an isReactive object

grammar

const val = isReactive({})
isRef(val) // true

18.3,isReadonly

Check whether an object is a read-only proxy created by readonly

grammar

const state = reactive({
  name: 'John'
})
console.log(isReactive(state)) // true

18.4,isProxy

Check whether the object is a proxy created by reactive or readonly

grammar

const state = reactive({
  name: 'John'
})
console.log(isProxy(state)) // true

19. Report mobile dom component

Teleport provides a clean method that allows us to control which parent node in the DOM renders HTML without resorting to the global state or splitting it into two components.

grammar

<teleport to="Move position">
	<div v-if="isShow" class="mask">
		<div class="dialog">
			<h3>I am a pop-up window</h3>
			<button @click="isShow = false">Close pop-up window</button>
		</div>
	</div>
</teleport>


// to format
<teleport to="#some-id" />
<teleport to=".some-class" />
<teleport to="[data-teleport]" />

// disabled format
<teleport to="#popup" :disabled="displayVideoInline">
  <video src="./my-movie.mp4">
</teleport>

20. Suspend asynchronous rendering component

When waiting for asynchronous components, render some additional content first to make the application have a better user experience

grammar

<template>
	<div class="app">
		<h3>I am App assembly</h3>
		<Suspense>
			<template #default>
				<Child/>
			</template>
			<template #fallback>
				<h3>Loading.....</h3>
			</template>
		</Suspense>
	</div>
</template>


import { defineAsyncComponent } from 'vue'
const Child = defineAsyncComponent(() => import('./components/Child.vue'))

components: {
    Child
}

21. Global API adjustment

Adjust the global API, Vue.xxx, to the application instance (app)

V2 api V3 api
Vue.config.xxxx app.config.xxxx
Vue.component app.component
Vue.directive app.directive
Vue.mixin app.mixin
Vue.use app.use
Vue.prototype app.config.globalProperties

22. Remove api

name present situation
Vue.config.productionTip Removed
config.keyCodes Removed
$children Removed
$listeners Removed
$on Removed
$off Removed
$once Removed
filters Removed
.native Removed

23. Ref get DOM

Since this does not exist in V3, the acquisition of ref is adjusted

23.1, single ref

grammar

<div ref="Qrcode" class="qr_codeode_url" />

import { ref } from 'vue'

export default {
  setup() {
    const Qrcode = ref(null)
    // After mounting
	onMounted(() => {
		console.log(Qrcode.value)
	})
    return {
      Qrcode
    }
  }
}

23.2, ref in cycle

Binding ref on a for loop element in V3 will no longer automatically create a $ref array. To get multiple refs from a single binding, bind refs to a more flexible function

grammar

<div v-for="item in list" :ref="setItemRef"></div>

import { onBeforeUpdate, onUpdated } from 'vue'

export default {
  setup() {
    let itemRefs = []
    const setItemRef = el => {
      if (el) {
        itemRefs.push(el)
      }
    }
    onBeforeUpdate(() => {
      itemRefs = []
    })
    onUpdated(() => {
      console.log(itemRefs)
    })
    return {
      setItemRef
    }
  }
}
  • Itemref does not have to be an array: it can also be an object whose ref can be set through the iterative key
  • If necessary, itemRef can also be responsive and can be listened on

24. emits custom event

Define events that a component can trigger to its parent component

// In subcomponents
<h1 @click="father">{{ msg }}</h1>

export default {
	name: 'HelloWorld',
	props: {
		msg: {
			type: String,
			default: ''
		}
	},
	emits: ['close'],
	setup(props, { emit }) {
		const father = function() {
			emit('close', 'child')
		}
		return {
			father
		}
	}
}

// In parent component
<HelloWorld :msg="msg" @click="fn" @close="fn2" />

25, $nextTick asynchronous update

Usage modification

import { nextTick } from 'vue'

nextTick(() => {
  // ...
})

26. hook life cycle events

Listen for critical phases in the component life cycle through events

grammar

// Syntax of V2
<template>
  <child-component @hook:updated="onUpdated">
</template>

// Syntax of V3
<template>
  <child-component @vnode-updated="onUpdated">
</template>

// Hump writing
<template>
  <child-component @vnodeUpdated="onUpdated">
</template

If you find it helpful, I'm @ pengduoduo. Welcome to praise and pay attention to comments; END

PS: press F12 on this page, and enter document.querySelectorAll('.diggit')[0].click() in the console. What a surprise

official account

Previous articles

Personal home page

Tags: Vue.js

Posted on Sun, 31 Oct 2021 21:37:21 -0400 by deepermethod