Vue3.0 has advantages over VUe2.0
- Compared with VUe2.0, the performance of VUe3.0 has been improved by nearly 50%. A lot of performance optimization has been made in the framework, including virtual DOM, compiled templates, new data listening of Proxy, smaller package files, etc
- Vue3.0’s new Composition API organizes code according to logical dependencies. Compared with the Options API of VUe2.0, the Composition API improves the readability and maintainability of code, and is more suitable for writing large projects
- Vue3.0 supports Typescript better, removing the cumbersome this operation, and more powerful type derivation
Vue3.0 is different from VUe2.0 in syntax
-
Vue3.0 supports the use of multiple root nodes in components to reduce the depth of the node hierarchy and also expects developers to be clear about the semantics
-
Vue3.0 has removed filters and will no longer be supported, and has officially recommended using computed attributes to replace filters
-
Vue3.0 exposes a number of apis for developers to use, which can be imported from Vue as required. Taking tree-shaking into consideration, the import and export syntax is used to package modules on demand
-
A new global API createApp was added to Vue3.0. Calling createApp returns an application instance that exposes the global API (Vue3.0 transfers the API that can change the behavior of the Vue globally from the original Vue constructor to the instance).
/ / vue2.0 created import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false new Vue({ render: h= > h(App), }).$mount('#app') / / vue3.0 created import { createApp } from 'vue' import App from './App.vue' createApp(App).mount('#app'); Copy the code
Vue3.0 compares vue2.0 responsiveness
Object.defineproperty can only listen to read and write of attributes, while Proxy can also listen to delete attributes and call methods in addition to read and write
vue2.0
The principle of data responsivity is to use data by iterating through data attributesObject.definePrototype
Convert it to a setter/getter, publish a message to the subscriber when the data changes, and trigger the corresponding listening callback. Due to the limitations of JS, VUE cannot detect the addition and deletion of array and object propertiesvue3.0
Based on theProxy
To do the data hijacking proxy, can native support to the array of response type, do not need to rewrite the array prototype, can also directly detect array and object properties of the new and delete (solve vue2.0 can not detect array and object properties of the add and delete problem)
Vue3.0 supports Typescript better
- Typescript is a superset of javascript types that can be compiled into pure javascript
- Typescript runs on any browser, any computer, and any operating system, and is open source
- Typescript provides static type checking, standardizing how teams code and use it, and makes it suitable for large projects
- IDE friendly tips are also suitable for large project development
Vue3.0 commonly used API
Vue combined API:composition-api.vuejs.org/zh/api.html…
setup
The setup function is a new component option that serves as an entry to using the Composition API within a component, where variables and methods are defined
- The setup function replaces the beforeCreate and Created lifecycle functions and is called before the lifecycle beforeCreate
- This is not available in setup() and the declared variable name is used to access the data directly. (Since setup() is called before parsing the 2.x option, this in setup() will be completely different from this in the 2.x option. Using this in both setup() and 2.x options causes confusion.)
- The setup function takes two arguments:
props
和context
:- The props object is the name of the parameter that the component is allowed to pass and the corresponding value of the response
- Context is a context object that exposes three attributes: attrs, slots, and emit
- Use variables defined within the setup function
return
Exposed for use in the template
<template>
<div>
{{ count }}
{{ obj.count }}
</div>
</template>
<script>
// Import the required API
import { ref, reactive } from 'vue'
export default {
name: 'home'.setup() {
const count = ref(0)
export let obj = reactive({ count: 0 })
// Exposed by return for use in template
return {
count,
obj
}
}
}
</script>
<style scoped>
</style>
Copy the code
Using the < script setup >
- When the < script> tag has the setup attribute, the context in which the component’s code is run during compilation is in the setup() function
- Define the variable used
export
Exposed for use in the template
<template>
<div>
{{ count }}
{{ obj.count }}
</div>
</template>
<script setup>
// Import the required API
import { ref, reactive } from 'vue'
// It is exposed by export for use in template
export let num = ref(0)
export let obj = reactive({ count: 0 })
</script>
<style scoped>
</style>
Copy the code
reactive
Reactive receives a common object and returns a reactive proxy for that common object, creating a reactive data object
<template>
<div>
{{ obj.count }}
</div>
</template>
<script>
// Import the required API
import { reactive } from 'vue'
export default {
name: 'home'.setup() {
// Reactive defines reactive objects
const obj = reactive({ count: 0 })
// Exposed by return for use in template
return {
obj
}
}
}
</script>
Copy the code
ref
Ref takes a parameter value and returns a responsive and mutable REF object. The ref object has a single.value attribute that points to an internal value
- Reactive ({value: obj}) reactive({value: obj})
- Use.value when accessing a ref-wrapped object in the setup function, and access it in the template template automatically identifies whether it is ref-wrapped, eliminating the need to write an additional.value inside the template
<template>
<div>
{{ count }}
</div>
</template>
<script>
// Import the required API
import { ref } from 'vue'
export default {
name: 'home'.setup() {
// Define reactive objects through ref
const count = ref(0)
// Access the value via the value attribute
console.log(count.value) / / 0
// Exposed by return for use in template
return {
count
}
}
}
</script>
Copy the code
toRef
ToRef can be used to create a REF for properties of a Reactive object, which can be passed and remain responsive (converting a value in a Reactive object to reactive data).
Difference with REF:
- Ref is a copy of the incoming data, and toRef is a reference to the incoming data
- A change in the value of ref updates the view; a change in the value of toRef does not update the view
<script>
// Import the required API
import { reactive, toRef } from 'vue'
export default {
name: 'home'.setup() {
// Reactive defines reactive objects
const obj = reactive({ count: 0.name: Daniel Wu of Langfang })
// Create the count attribute in obj as ref by toRef
const count = toRef(obj, 'count')
// Exposed by return for use in template
return {
obj,
count
}
}
}
</script>
Copy the code
toRefs
ToRefs converts a reactive object into a normal object, each property of which is a REF, corresponding to a reactive object property (converting all values in a Reactive object to reactive data).
<script>
// Import the required API
import { reactive, toRefs } from 'vue'
export default {
name: 'home'.setup() {
// Reactive defines reactive objects
const obj = reactive({ count: 0.name: Daniel Wu of Langfang })
// Create all attributes in obj as refs via toRefs
const refObj = toRefs(obj)
console.log(refObj)
// Exposed by return for use in template
return {
obj,
refObj
}
}
}
</script>
Copy the code
The console. The log (refObj) :
readonly
Readonly Passes in an object (reactive or plain) or ref and returns a read-only proxy of the original object (which cannot be modified)
- A read-only proxy is “deep” and any nested properties inside an object are also read-only
<template>
<div>
{{ count }}
</div>
</template>
<script>
// Import the required API
import { readonly } from 'vue'
export default {
name: 'home'.setup() {
// Define a read-only object with readonly
const count = readonly(0)
count.value++ // Modify error! Cannot create property 'value' on number '0'
// Exposed by return for use in template
return {
count
}
}
}
</script>
Copy the code
computed
Computed (computed properties) passes in a getter function that returns a ref object that cannot be manually modified by default, and is used much differently than VUE 2.0
<template>
<div>
{{ count }}
{{ addCount }}
</div>
</template>
<script>
// Import the required API
import { ref, computed } from 'vue'
export default {
name: 'home'.setup() {
// Define reactive objects through ref
const count = ref(0)
// Implement computed attributes using a computed method
const addCount = computed(() = > count.value + 1)
console.log(addCount.value) / / 1
// Exposed by return for use in template
return {
count,
addCount
}
}
}
</script>
Copy the code
watch
Watch (listener) needs to listen for a specific data source and perform side effects in the callback function, not much different from VUE 2.0
- The default is lazy, executing callbacks only when the source changes are being listened for
<script>
// Import the required API
import { ref, reactive, watch } from 'vue'
export default {
name: 'home'.setup() {
// Define reactive objects through ref
const count = ref(0)
// Use the watch method to listen for count data
watch(count, (newVal, oldVal) = > {
console.log('newVal:' + newVal)
console.log('oldVal:' + oldVal)
})
// Reactive defines reactive objects
const obj = reactive({ count: 0 })
// Use the watch method to listen for obj.count
watch(() = > obj.count, (newVal, oldVal) = > {
console.log('newVal:' + newVal)
console.log('oldVal:' + oldVal)
})
// Use the watch method to listen for both count and obj.count
watch([count, () = > obj.count], ([newVal1, oldVal1], [newVal2, oldVal2]) = > {
console.log('newVal1:' + newVal1)
console.log('oldVal1:' + oldVal1)
console.log('newVal2:' + newVal2)
console.log('oldVal3:' + oldVal2)
})
// Exposed by return for use in template
return {
count,
obj
}
}
}
</script>
Copy the code
watchEffect
WatchEffect executes a function passed in immediately, traces its dependencies responsively, and rerunts the function when its dependencies change
- When watchEffect is called in a component’s setup() function or lifecycle hook, the listener is linked to the component’s lifecycle and stops automatically when the component is unloaded (the return value can also be explicitly called to stop listening)
// The watchEffect method returns the stop method, which is executed to stop listening const stop = watchEffect(() = >{... })// Stop listening stop() Copy the code
Differences with Watch:
- No need to manually pass in dependencies (no need to manually specify listening objects)
- A callback function is executed for each initialization to automatically retrieve dependencies
- You can only get the changed value, not the original value.
<script>
// Import the required API
import { ref, reactive, watchEffect } from 'vue'
export default {
name: 'home'.setup() {
// Define reactive objects through ref
const count = ref(0)
// Reactive defines reactive objects
const obj = reactive({ count: 0 })
// Use the watchEffect method to listen for data (only the changed value is available)
watchEffect(() = > {
console.log(count.value)
console.log(obj.name)
})
// Exposed by return for use in template
return {
count,
obj
}
}
}
</script>
Copy the code
Template Refs
When using composite apis, reactive refs and Template Refs are unified. To get a reference to an element or component instance within a template, declare a ref with a value of null in setup() and return it
- The variable name must be the same as the name set by the element ref = box: const box = ref(null)
<template>
<div ref="box"></div>
</template>
<script>
// Import the required API
import { ref, onMounted } from 'vue'
export default {
name: 'home'.setup() {
// Get the specified element by ref(null)
const box = ref(null)
onMounted(() = > {
console.log(box.value) //<div></div>
})
// Exposed by return for use in template
return {
box
}
}
}
</script>
Copy the code
Vue3.0 life cycle
-
Vue3.0 life cycle section changes (setup functions instead of beforeCreate and created life cycle functions are called before life cycle beforeCreate)
Vue 2.0 vue3.0 beforeCreate setup created setup beforeMount onBeforeMount mounted onMounted beforeUpdate onBeforeUpdate updated onUpdated beforeDestory onBeforeUnmount destoryed onUnmounted -
To use the lifecycle of VUe3.0, you also need to import it from vUE and use it in setup functions
<script> // Introduce the life cycle import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, unMounted } from 'vue' export default { name: 'home'.setup() { // Components before mounting onBeforeMount(() = >{... })// Before and after components are mounted onMounted(() = >{... })// Before component update onBeforeUpdate(() = >{... })// After component update onUpdated(() = >{... })// Before component destruction onBeforeUnmount(() = >{... })// After the component is destroyed unMounted(() = >{... })return{... } } } </script>Copy the code
The new vue3.0 syntax is used in the VUe2.0 project
- Vue official @vue/ composition-API plugin: github.com/vuejs/compo…
Install @ vue/composition – API:
npm install @vue/composition-api –save
The main. Js:
import Vue from 'vue'
import App from './App.vue'
/ / incoming @ vue/composition - API
import VueCompositionAPI from '@vue/composition-api'
Vue.use(VueCompositionAPI)
Vue.config.productionTip = false
new Vue({
render: h= > h(App),
}).$mount('#app')
Copy the code
Vue-cli4 Creates a Vue3.0 project
- Scaffolding requirements: VUE-CLI4.0 or above
npm install -g @vue/cli
Create a vue3.0 project using vue li4 scaffolding:
Vue create vue3.0 – demo
Select the Vue 3
Route configuration:
Vue3.0 vuE-Router4.0 API:
- CreateRouter: Creates a route instance
- CreateWebHashHistory: Creates the hash routing mode
- CreateWebHistory: Creates the history routing mode
Routing file router.js:
// Import the routing API
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '.. /views/home/index.vue'
import About from '.. /views/about/index.vue'
// Create a hash routing mode
const routerHashHistory = createWebHashHistory()
// Create a routing instance
const router = createRouter({
history: routerHashHistory,
routes: [{name: 'home'.path: '/'.component: Home
},
{
name: 'about'.path: '/about'.component: About
}
]
})
export default router
Copy the code
The main. Js:
import { createApp } from 'vue'
import App from './App.vue'
// Import the route instance
import router from './router'
// Inject the routing instance into the vue root instance
createApp(App).use(router).mount('#app')
Copy the code