- Ref and toRef, toRefs
The ref function wraps a responsive data object. ToRef converts a value in an object to reactive data. It takes two parameters. The first parameter is an obj object. The second argument is the name of the property in the object. ToRefs converts the values of all attributes in the passed object to reactive data objects. This function supports one argument: obj object ref is a copy of the passed data; ToRef is a reference to the incoming data and changes in the value of ref will update the view; Changes in the value of toRef do not update the view
- Reactive and shallowReactive
The reactive method is used to create a reactive data object. It can be a nested object. It adds a Proxy to each object inside the object. Proxy is added to the first layer only when used
<template>
<div>{{state.count}}</div>
</template>
<script>
import { reactive,shallowReactive }from 'vue'
export default {
name: 'HelloWorld',
props: {
msg: String
},
setup() {
const state= reactive({count:3})
return {
state
}
}
}
</script>
Copy the code
Now compare reactive with shallowReactive using reactive
<template> <div>{{state.count}}</div> </template> <script> import { reactive,shallowReactive }from 'vue' export default { name: 'HelloWorld', props: { msg: String}, setup() {const obj={one:{name:' xiao Ming ', two:{name:' xiao Wang ', three:{name:' Xiao Li ', } } } } const state= reactive(obj) console.log(state.one) console.log(state.one.two) console.log(state.one.two.three) return { state } } } </script>Copy the code
Using shallowReactive
<template> <div>{{state.count}}</div> </template> <script> import { reactive,shallowReactive }from 'vue' export default { name: 'HelloWorld', props: { msg: String}, setup() {const obj={one:{name:' xiao Ming ', two:{name:' xiao Wang ', three:{name:' Xiao Li ', } } } } const state= shallowReactive(obj) console.log(state) console.log(state.one) console.log(state.one.two) console.log(state.one.two.three) return { state } } } </script>Copy the code
The running results are as follows:
4. The toRaw and markRaw toRaw methods are used to obtain raw data from the ref or reactive object. The following is an example:
<script> import {reactive, toRaw} from 'vue' export default {setup() {const obj = {name: 'reactive ', age: 35 } const state = reactive(obj) const raw = toRaw(state) console.log(state) console.log(raw) console.log(obj === raw) // true } } </script>Copy the code
Here are the results:
markRaw
Method can mark raw data as non-responsive, that is, useref
或 reactive
Wrap it, still unable to achieve data response, which takes a parameter, the original data, and returns the marked data. The following is an example:
<script> import {reactive, toRaw,markRaw} from 'vue' export default {setup() {const obj = {name: 'reactive, toRaw,markRaw ', age: 35 } markRaw(obj) const state = reactive(obj) console.log(obj) console.log(state) } } </script>Copy the code
Results:
5. UseRoute and useRouter
<template> <div> <router-link to="/home">Home</router-link> <router-link to='/test'>Test</router-link> </div> <router-view></router-view> </template> <script> import { onMounted } from "vue"; import { useRoute, useRouter } from "vue-router"; export default { setup(props, context) { onMounted(() => { console.log(route); console.log(router); }); const route = useRoute(); const router = useRouter(); return {}; }}; </script>Copy the code
6. Watch and watchEffectwatch
andwatchEffect
Are used to monitor changes in data to perform specified operations, but there are differences in usage:
watch( source, cb, [options] )
- Source: Can be an expression or function that specifies the dependent object to listen on
- Cb: the callback function that is executed after the dependent object changes
- Options: Parameters that can be configured include immediate (triggers callbacks immediately) and deep (deep listener).
When the ref
<template> <div> <router-link to="/home">Home</router-link> <router-link to='/test'>Test</router-link> </div> <router-view></router-view> </template> <script> import { ref,watch} from "vue"; export default { setup() { const state = ref(0) watch(state, (newValue, OldValue) => {console.log(' original value ${oldValue} ') console.log(' newValue ${newValue} ') /* print the result after 1 second: SetTimeout (() => {state.value ++}, 1000)},}; </script>Copy the code
When the reactive
<script> import {reactive, watch} from 'vue' export default { setup() { const state = reactive({count: 0}) watch(() => state.count, (newValue, OldValue) => {console.log(' original value ${oldValue} ') console.log(' newValue ${newValue} ') /* print the result after 1 second: SetTimeout (() => {state.count ++}, 1000)}} </script>Copy the code
Here are the results:
Listen for multiple values:
<script> import {reactive, watch} from 'vue' export default { setup() { const state = reactive({ count: 0, name: 'zs' }) watch( [() => state.count, () => state.name], ([newCount, newName], [oldvCount, OldName]) => {console.log(oldvCount) // old count value console.log(newCount) // newCount value console.log(oldName) // oldName Value console.log(newName) // newName value}) setTimeout(() => {state.count ++ state.name = 'ls'}, 1000)}} </script>Copy the code
Here are the results:
WatchEffect, it differs from Watch mainly in the following points:
- There is no need to manually pass in dependencies
- A callback function is executed on each initialization to automatically acquire dependencies
- You cannot get the original value, only the changed value
<template> <div> <router-link to="/home">Home</router-link> <router-link to='/test'>Test</router-link> </div> <router-view></router-view> </template> <script> import {reactive, watchEffect} from 'vue' export default { setup() { const state = reactive({ count: 0, name: 'zs'}) watchEffect(() => {console.log(state.count) console.log(state.name) /* Print when initialization: 0 1 ls */ }) setTimeout(() => { state.count ++ state.name = 'ls' }, 1000) } } </script>Copy the code
7.computed returns a ref object.
<script>
import {computed,ref} from 'vue'
export default {
setup() {
const x=computed(()=>{
return 'jjjjj'
})
console.log(x.value)
const count = ref(1)
const plusOne = computed({
get: () => {
console.log('---------Get',count.value)
return count.value + 1
},
set: val => {
console.log('---------Set',val)
count.value = val - 1
}
})
plusOne.value = 1
console.log(count.value)
}
}
</script>
Copy the code
Here are the results:
8. Dojo.provide and inject
- provide: Passes data to child and descendant components. Receive two parameters, the first parameter is
key
, the name of the data; The second parameter isvalue
, which is the value of the data - inject: Receives data from the parent or ancestor component. Receive a parameter
key
Is the name of the data passed by the parent or ancestor component
//a.vue <script> import {provide} from 'vue' export default {setup() {const obj= {name: 'hahaha hahaha ', age: } provide('info', 'info', 'info', 'info'); Obj)}} </script> //b.vue <script> import {inject} from 'vue' export default {setup() {// receive data from a.vue Inject ('info') // {name: 'hahahahahaha ', age: 22}}} </script> //c.vue <script> import {inject} from 'vue' export default {setup() {// receive data from a.vue Inject (' info ') / / {name: "ha ha ha ha ha ha, age: 22}}} < / script >Copy the code
9. Life cycle comparison between VUE2 and VUE3
<template> <div id="app"></div> </template> <script> // 1. Import {onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, unMounted} from 'vue' export default { name: 'App', Setup () {onBeforeMount(() => {// Execute some code before mounting}) onMounted(() => {// Execute some code after mounting}) onBeforeUpdate(() => {// OnBeforeUnmount (() => {// Execute some code before component is destroyed}) unMounted(() => {// Execute some code before component is destroyed}) unMounted(() => {// Return {}}} </script>Copy the code
10.setup(props,context)
(1)props: Const {title} = toRefs(props) (2)context: const {title} = toRefs(props) (2)context: $attrs component tag (non-responsive object) context.slots this.$slots slot (non-responsive object) context.emit this.$emit The custom trigger event (method) context.emit(' custom event name ', argument) on the tag is not accessible: because it points to data computed Methods before the component creates the instance: The context is a normal JavaScript object, that is, it is not reactive and can be deconstructed directly. Attrs and Slots are proxies for the corresponding values on the internal component instance. This ensures that they always show the latest values even after they are updated, so that we can structure them without worrying about accessing old references: but avoid deconstructing the internal properties, and always use them in the manner of attrs.x or slots. Because setup() is called before the other component options are resolved, this inside setup() behaves completely differently than this in the other options. You can import functions, etc., from other files, and then execute them in setup. Other files can use the combined API of V3 (which must be imported first), but must be called in setup. Return {return properties and methods that can be used outside of setup, and return normal properties that are not responsive, i.e. changes do not update the view} return () => h('div', [" Waka "]) can also directly return a render function that will replace the content in the template in way three: Note that the component has become an asynchronous component at this point and can be suspended using Suspense Return new Promise((resolve,reject)=>{return Promise((resolve,reject)=>{return Promise((resolve,reject)=>{return Promise((resolve,reject)=>{return Promise()); Resolve ({data})}) return await...Copy the code