Vue3.0 introduction
Just yesterday Rain Creek released itVUE3.0 BetaVersion. Next, the similarities and differences between VUe2.0 and 3.0 will be introduced
First, take the first step
Note: When using Vue 3.0, it is best to upgrade your vue scaffolding tool to the latest CLI 4.x. I failed to execute vue add vue-next on CLI3. x. NPM install -g@vue /cli after installation, run vue -v to check the version number.
1. Firstly, I initialized the project with cli4 scaffolding tool. In order to compare the two VUE versions, I initialized two projects and named the folders vue2.0 and vue3.0 respectively.
After initialization, go to the package.json file in the root path, because the current cli4.x project is still using vue2.0
We can now upgrade the current vUE version of the project to 3.0 beta by typing vue add vue-next in the command line tool. The installation is successful if the following configuration appears
Changes to VUE 3.0
We’ll start by opening the main.js file, which has some changes from previous versions:
Vue3.0 import {createApp} from 'vue'; Import App from './ app.vue 'createApp(App).mount('# App ') //vue2.0 import vue from 'vue' import App from './ app.vue' Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app')Copy the code
Using the above code we can see that 3.0 is much more streamlined than 2.0 and introduces a new function named createApp to which containers will be mounted.
Three, get down to business
I’ll compare 2.0 and 3.0 in terms of the following attributes and common methods:
- Data
- Method
- LifeCycle
- Computed
- Components
- Props
- Emit
1. Data:
Export default {data(){return{}}, Mounted (){}, methods:{}, computed:{}}, /////////////////////// instead uses the following method to initialize data: <template> <div class="hello"> 123 </div> <div>{{name.name}}</div> </template> import {reactive} from 'vue' export Default {setup(){const name = reactive({name:'hello '}) return {name}}}Copy the code
Setup is equivalent to beforeCreate and Created in previous 2.0 releases. It is executed when the component is initialized, or even before Created. Note that in 3.0, if you want to use setup data, you need to return the value, which is available in the template.
If you don’t return, the browser will tell you:
runtime-core.esm-bundler.js?5c40:37 [Vue warn]: Property "name" was accessed during render but is not defined on instance.
at <Anonymous>
at <Anonymous> (Root)
Copy the code
This is also something to be aware of in 3.0. If you are aware, I have added two child nodes to the template, which is not allowed in 2.0. This is also a minor change in 3.0, and Reactive is a way of responding to data in 3.0. It mainly responds to data on objects.
2.Method
<template> <div class="hello"> <div>{{name.name}}</div> <div>{{count}}</div> <button @click="increamt">button</button> </div> </template> <script> import {reactive,ref} from 'vue' export default {setup(){const name = reactive({name:' king ') }) const count=ref(0) const increamt=()=>{ count.value++ } return {name,count,increamt} } }Copy the code
In the Method code, I refer to vue’s new ref function, which creates a reference to a String,Number, or Boolean response. And one might say, well, why don’t you just assign count instead of ref(0), and the way I understand it is, if you just assign count you’re throwing it out, it’s hard to find, and ref means you’re throwing it out at the same time, You put a rope around it so you could track it. Notice how, in the ref function, you want to change or reference its value, the ref method provides a return value of value and operates on that value.
The LifeCycle in 3.0 is very different from that in 2.0:
-
BeforeCreate -> Please use setup()
-
Created -> Setup ()
-
beforeMount -> onBeforeMount
-
mounted -> onMounted
-
beforeUpdate -> onBeforeUpdate
-
updated -> onUpdated
-
beforeDestroy -> onBeforeUnmount
-
destroyed -> onUnmounted
-
errorCaptured -> onErrorCaptured
If you want to use life cycle functions in a page, the previous 2.0 operation was to write the life cycle directly in the page, but now you need to reference it, which is why 3.0 is able to compress the code even lower.
import {reactive, ref, OnMounted} from 'vue' export default {setup(){const name = reactive({name:' king '}) const count=ref(0) const increamt=()=>{ count.value++ } onMounted(()=>{ console.log('123') }) return {name,count,increamt} }Copy the code
Here’s an example:
In the past, 2.0 was like eating in a restaurant. We waited for the dishes to arrive before we started eating, and sometimes ordering too much would lead to unnecessary waste. Now 3.0 is more like a buffet — you take as much as you eat, so you don’t waste it.
4.computed
< the template > < div class = "hello" > < div > {{name. The name}} < / div > < div > {{count}} < / div > < div > calculate attribute {{computeCount}} < / div > < button @click="increamt">button</button> </div> </template> <script> import {reactive, ref, OnMounted,computed} from 'vue' export default {setup(){const name = reactive({name:' king '}) const count=ref(0) const Increamt =()=>{count.value++} const computeCount=computed(()=>count.value*10) This is new to 3.0 easy to forget things onMounted (() = > {the console. The log (' 123 ')}) return {name, count, increamt, computeCount}}} < / script >Copy the code
Let’s discuss the use of vue3.0 components again
Before we get into the use of 3.0 components, we can review the way 2.0 uses components. In 2.0, the component is imported to the page where it is needed and registered on the page. When passing parameters, the parent component passes parameters to the child component, which receives the parameters from the parent.
Here’s an example:
Parent <template> <div id="app"> <HelloWorld MSG ="Welcome to Your vue.js app" @childclick="parentClick"/> </div> </template> <script> import HelloWorld from './components/HelloWorld.vue' export default { name: 'App', components: { HelloWorld }, Methods :{parentClick(e){console.log(e)// '123'}}}</ script> subcomponent <template> <div class="hello"> <h1>{{MSG}}</h1> </div> </template> <script> export default { name: 'HelloWorld', props: { msg: String }, data(){ return{ } }, method:{ handleClick(){ this.$emit('childclick','123') } } } </script>Copy the code
These are the most common calls between parent and child components, but there are differences in VUe3.0.
No more nonsense, first on the DJ(code)! DJ first (code)!!
The parent component
<template> <div class="hello"> <div>123</div> <NewComp :name="name" @childClick="parentClick"/> </div> </template> <script> import {reactive} from 'vue' import NewComp from './newComp.vue' export default { components:{ NewComp }, Setup (){const name=ref('hello tomatos ') const parentClick=(e)=>{console.log(e) console.log('123')} return {name,parentClick} } } </script>Copy the code
Child components
<template> <div> <button @click="handleClick">{{props.name}}</button> </div> </template> <script> export default { Props :{name:String} setup(props,{emit}){const handleClick=()=>{console.log(props)//proxy{name:' Hello '} emit('childClick','hello') } return { props, handleClick } } } </script>Copy the code
From the invocation between vue3.0 parent and child components above, we can find that the invocation of the parent component is basically the same as that of 2.0. In the child component, to obtain the parameters passed by the parent component, we directly obtain props and emit events in setup(). This is because setup provides the props and context properties, and the context contains events such as emit. One might look at this and ask, why not use this.$emit to emit child component events? Since this is no longer used in 3.0, when you print this in setup(), the output will be undefined.
Logic reuse in VUe3.0
In VUe2.0, if we want to reuse logic, we usually use mixins to import the required function methods. When using this method, there are many disadvantages, such as:
Variable conflicts: When too many mixins are used, variable name conflicts are inevitable.
Here’s an example:
<template> <div class="hello"> <h1>{{MSG}}</h1> < button@click ="hello"> button </button> </div> </template> <script> import useResize from '.. /libs/size.js' export default { mixins:[useResize], name: 'HelloWorld', props: { msg: String }, data(){ return{ } }, methods:{ } } </script>Copy the code
Mixins components
export default {
data() {
return {
msg: "width"
}
},
methods: {
hello() {
console.log("hello")
}
},
mounted() {
console.log(this.msg)
}
}
Copy the code
This is where the problem of duplicate variable names arises.
How does that work in VUe3.0? Here’s another chestnut:
<template> <div class="hello"> <h1>{{ name }}</h1> <h1>{{obj.tall}}</h1> <button @click="onClick">Boom</button> < h1 > {{num}} < / h1 > < h1 > {{changeCount}} < / h1 > < button @ click = "incream" > add < / button > < h1 > {{WidthResize}} < / h1 > < / div > </template> <script> import { ref, reactive, computed } from "vue"; import {useResize} from '.. String,Number,Boolean Const name=ref('hello, tomato ') // export default {setup(){//ref => ref('hello, tomato ') Const obj=reactive({tall:'180'}) const onClick=()=>{obj.tall="200", Name. value=" Time to eat "} const incream=()=>{num. Value ++} const changeCount=computed(()=> num. Value *2) const {incream=()=>{num. Width :WidthResize} = useResize(); Return {name, obj, num, WidthResize,// return the used variable name onClick, changeCount, incream } } } </script>Copy the code
Vue3.0 reuse logical files
import { ref, onMounted, onUnmounted } from 'vue'
export function useResize(){
const width=ref('width')
const height=ref('Height')
const update=()=>{
width.value='hello Width'
height.value='hello Height'
}
onMounted(()=>{
window.addEventListener('resize',update)
})
onUnmounted(()=>{
window.removeEventListener('resize',update)
})
return {
width,height
}
}
Copy the code
Data source is not very clear: when there is too much code, it is difficult to easily trace the source of the source variable.
One more chestnut
In Vue2.0, it is difficult to find the source of a variable when there is too much code, even if the variable comes from another file. As mentioned above with mixins, if you haven’t used mixins before and you don’t even know where the hello method comes from, it can be very confusing to read the code.
Vue3.0 optimizes this problem because in 3.0, all variables are local variables, making it easier to find variables or method names.
Six, summarized
Vue3.0 vs vue2.0
- Changes:
- Ref () is used for references to common types of values (String,Number,Boolean) and for assignments, xx. Value =’ XXX ‘is used for references to changed assignments.
- Reactive ({}) for assignment of object types
- Life cycle changes
- Method, evaluate properties, and listen for changes to properties
- Optimization:
- The improvement of logic reuse solves the problem of variable name conflict and traceability difficulty