As we all know, the front-end technology has been updated quickly, this vuE3 has been released for so long, today to share with you the vuE3 knowledge points worth noting. Like the words suggest collection, point a concern!
1, createApp
There are significant differences between vue2 and VUe3 when creating instances. The specific comparison is as follows:
//Vue 2
Vue.use({
router,
store,
render:h=>h(App)
}).$mount("#app")
//Vue 3
createApp(App).use(router).use(store).mount("#app")
Copy the code
Vue2 creates the instance using the router and store corresponding to new Vue().
In VUe3, the createApp is used to create the application instance, and the router and store are called as plug-ins by chain.
In VUe2, creating multiple instances will cause instance contamination if mixin, prototype, etc. The createApp method creates a completely new instance and avoids this problem. So in VUe3, you can create as many instances as you want.
2, the setup
Vue2 adopts optional development, while VUE3 adopts composite development and can also be downward compatible with optional development.
The setup function is the entry point to the Composition API in Vue3 and sits between the lifecycle hook functions beforeCreate and Created, so properties and methods in setup cannot be used externally. Return must be exposed if needed.
Compare the differences between vue2 and VUe3 in using data and method:
Vue2 export default{data(){return{name:" I love the front end "}, Methods :{print(){console.log(" print ")}}}} // vue3 export default{setup(){const name=" love front-end "function print(){ Console. log(" print ")} return {name, print}}}Copy the code
In VUE2, this is our regular customer and can be seen everywhere. Setup prints this and tries to see the result. The result is undefined.
So you can’t use this or mount anything related to this inside setup.
So the setup function provides two arguments:
Setup (props,context){//props is a responsive object, and cannot be used to decompose an object. // Attribute (non-responsive object) console.log(context.attrs) // slot (non-responsive object) console.log(context.slots) // Trigger events (methods) console.log(context.emit) }Copy the code
Script setup syntax sugar
Simplifying the setup composite API above is a new syntactic sugar for VUE3.
Features:
- Defined properties and methods can be used directly without a return.
- Automatically registers components, eliminating the need to register components within components.
Greatly simplifies the setup() code described above.
4. Hook functions
When vue2 uses lifecycle functions, use them directly. Such as:
// vue2
export default{
beforeCreate(){
},
mounted(){
}
}
Copy the code
However, in the Vue3 composite API, it is accessed by prefixing the lifecycle hook with on, which must be introduced before use. Such as:
// vue3
<script setup>
import { onMounted } from "vue"
onMounted(()=>{
})
</script>
Copy the code
Since setup runs around beforeCreate and Created lifecycle hooks, these two hook functions are not required within setup, and the rest is the same.
Official lifecycle hooks:
5. Teleport
Teleport can bind internal elements to any parent element in a simple and flexible way.
Usage:
<teleport to="body"></teleport>
Copy the code
The TO attribute is the DOM element that specifies the content to be added to the teleport. It can be a tag name, class name, or ID.
// Label name. The example above is added to the body element using the tag name. <teleport to="body"></teleport> // class name. To =".className" </teleport> //id <teleport to="#idName"></teleport>Copy the code
Advantages: When there are too many nested layers of components, the style layer is troublesome to handle. Teleport can be used to strip elements out, making it easy to set styles and vUE control state.
6, mixin
Mixin objects can extract options common to multiple components and introduce them into required components for easy management. Mixins are rarely used in VUe3.
Usage:
<script> const myMixin = {data(){return {name:' love front-end '}}} export default {mixins:[myMixin], Data (){return {QDR :" front-end person "}}} </script>Copy the code
When used, multiple mixin objects can be introduced. Precautions for use:
- Mixin objects are automatically merged when they contain the same options as components.
- When mixin objects have the same properties in the same options as components, the nearest rule preferentially inherits values from the instance.
- Mixins and components that contain the same hook function are executed together, with the hook function in the mixin taking precedence.
- When mixin custom attributes conflict with the instance, priority can be defined through optionMergeStrategies.
7. Custom instructions
Global custom directive:
The directive of VUe2 is mounted to the Vue object.
Vue3’s directive is mounted to app, for example:
//Vue 2
Vue.directive('name',opt)
//Vue 3
const app = createApp(App)
app.directive("name",options)
app.mount("#app")
Copy the code
Local custom instruction: same as vue2.
In VUe3, the custom instruction lifecycle hook functions are partially changed. The hook functions are as follows:
- created
- beforeMounted
- mounted
- beforeUpdate
- updated
- beforeUnmounted
- unmounted
Ref and Reactive
Ref is used to make the underlying type data responsive.
Reactive makes reference data types responsive.
Ref and Reactive wrap data to make it responsive and need to be imported before use.
The usage method is as follows:
<script setup>
import { ref , reactive } from "vue"
let mood = ref("value")
let me = reactive({
str:value,
})
</script>
Copy the code
Setup + REF + Reactive implements the reactive function of Data in VUe2, so setup can replace data.
9, toRefs, toRef
ToRefs is used to deconstruct the data passed by the props. Because the parent passes the value to the child component through the props is reactive, using ES6 deconstruction eliminates the reactive feature, so toRefs is used.
<script setup>
const props = defineProps({
selectNum:Number,
allNum:Number,
})
const { selectNum, allNum } = toRefs(props)
</script>
Copy the code
ToRef also deconstructs data, mainly for optional arguments. The runtime checks whether the attribute exists in the deconstructed data, inherits it if it does, and creates an attribute if it does not, so that no errors are reported.
const str = toRef( props, 'str' )
Copy the code
10, watch, watchEffect new usage
Watch and watchEffect are listeners.
Watch listens for an underlying type of data or a specific property that references the data type.
Vue3 must be introduced before using Watch.
//vue2 watch:{ mood(curVal,preVal){ console.log('cur',curVal); // Latest value console.log('pre',preVal); Vue3 import {watch} from "vue" watch(name, (curVal, preVal)=>{// Business processing}, options)Copy the code
WatchEffect listens for all properties that refer to the data type. It does not need to specify any particular property. Once run, it executes immediately.
Watcheffects must also be introduced before they can be used.
Import {watchEffect} from "vue" let obj = reactive({name:'qq',sex:' female '}) watchEffect(() => { console.log('name',obj.name); console.log('sex' , obj.sex); })Copy the code
Watch vs. watchEffect:
- The watchEffect does not execute immediately when the watch runs.
- Watch is more specific, you need to specify who to listen on, watchEffect does not execute specific listen on who, the callback function can be directly used, more abstract.
- The watch callback can access the previous value, and the watchEffect can only access the most recent value.
- Watch can be configured to implement the first two features of the watchEffect.
11. Computed New use
Computed properties
Vue2 and vue3 are used the same in the optional API.
In the composite API, it needs to be introduced before use.
// Optional computed:{sum(){return this.num1+ this.num2}} // Combinative import {ref, computed } from "vue" export default{ setup(){ const num1 = ref(1) const num2 = ref(1) let sum = computed(()=>{ return num1.value + num2.value }) } }Copy the code
Alternatively, it can use an object with get and set functions to create a writable object.
let mul = computed({
get:()=>{
return num1.value *10
},
set:(value)=>{
return num1.value = value/10
}
})
Copy the code
In vue3.2+, computed accepts an object with onTrack and onTrigger options as a second argument:
- OnTrack is called when a responsive property or ref is traced as a dependency.
- OnTrigger is called when the listening callback is triggered by a dependency modification.
12. Provide/inject
Provide /inject Similar to subscribing and publishing messages, provide provides or sends data or methods, and inject receives data or methods.
Advantages: There are many nested levels of components. When the parent component transmits values to its children and multiple grandson components, the data needs to be transmitted from one level to the next level, which is quite troublesome. Project and Inject are very convenient to solve this problem.
//vue2 export default{provide:{info:" Provide data "}} // Receive data export default{inject:['info'], Mounted (){console.log(" Receive data: ", this.info) // Receive data: }} //vue3 <script setup> import {provide} from "vue" provide('info', "Value") </script> // Receive data <script setup> import {inject} from "vue" const info = inject('info', "set defaults") </script>Copy the code
13, readonly
Readonly A read-only function. This data can only be used and cannot be modified.
If reactive data is passed between parent and child components, when the child changes, the parent component will also update, which can easily cause state confusion and does not conform to the single data flow of THE VUE.
If you use readonly, data can only be used in other components and cannot be modified to avoid confusion.
14. Get the real DOM
Vue2 uses $ref to get the real DOM.
Vue3 uses ref to get the real DOM. This is different from the ref above.
//vue2 <script> export default{mounted(){console.log('box', this.$refs.box); } } </script> //vue3 <script setup> const box = ref(null) onMounted(()=>{ console.log('box',box.value); }) </script>Copy the code
Vuex4 in VUe3
The createStore function creates a new store instance. It needs to be introduced before use.
import { createApp } from 'vue'
import App from './App.vue'
import { createStore } from "vuex"
const store = createStore({
state(){
return{
num:1,
}
}
})
const app = createApp(App)
app.use(store)
app.mount('#app')
Copy the code
When a store is used within a component, it is introduced through useStore, and it must be introduced before it is used.
import { useStore } from "vuex"
const store = useStore()
Copy the code
When used, it is the same as the lower version. When using in-state data, it can be deconstructed through toRefs.
16, v – slot
The V-slot directive can only be used with templates or components, otherwise an error will be reported.
Simplified slot, slot-scope scope slots, more powerful, more efficient code.
Use:
<child-com> <template v-slot:header> header </template> <template v-slot:body> content </template> </child-com>Copy the code
Abbreviations:
<child-com> <template #header> </template> <template #body> Content </template> </child-com>Copy the code
Vue-router4 in VUe3
CreateRouter creates the router instance. Change the previous mode to history.
import { createRouter,createWebHashHistory } from "vue-router";
const routes = []
const router = createRouter({
history:createWebHashHistory('/'),
routes
})
export default router
Copy the code
When introduced in main.js, it is referenced by use.
import { createApp } from 'vue'
import App from './App.vue'
import router from "./router/index"
const app = createApp(App)
app.use(router)
app.mount('#app')
Copy the code
There are a lot of updates to vue-Router4. For more information, read Vue-Router 4 are you Really Proficient? The article.
In the 18th and render
In VUe3, the parameters of the render function have been changed, the previous H has been removed, and the virtual node has a flat attribute structure.
Render application in VUe3
import { h } from "vue"
export default {
render(){
return h("div", {}, content)
}
}
Copy the code
Well xiaobian today’s article is over, like me can point a concern oh