Home  >  Article  >  Web Front-end  >  What is the difference between vue2 and vue3

What is the difference between vue2 and vue3

青灯夜游
青灯夜游Original
2022-08-26 18:13:4113159browse

Difference: 1. Vue2’s two-way data binding uses ES5’s API Object.definePropert(), while vue3 uses es6’s API Proxy; 2. Vue3 supports fragmentation, but vue2 does not; 3. Vue2 uses the option type API, while Vue3 uses the synthetic API; 4. To create data, vue2 puts the data into the data attribute, while Vue3 uses the setup() method; 5. vue3 has the Teleport component, but vue2 does not.

What is the difference between vue2 and vue3

The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.

Inventory of the differences between Vue3 and Vue2

1. The two-way data binding principle of vue2 and vue3 has changed

vue2's two-way data binding is implemented by using an API of ES5 Object.definePropert() to hijack data and combine it with the publish-subscribe mode.

vue3 uses es6’s ProxyAPI for data proxy.

Compared with vue2.x, the advantages of using proxy are as follows

  1. defineProperty can only monitor a certain property and cannot monitor the entire object
  2. Yes Eliminate for in, closure and other contents to improve efficiency (just bind the entire object directly)
  3. You can monitor the array, and you no longer need to perform specific operations on the array separately. vue3.x can detect the inside of the array. Changes in data

2. Vue3 supports fragments

That is to say, components can have multiple roots node.
vue2

<template>
  <div>
  <h2> {{ title }} </h2>
  </div>
</template>

vue3

<template>
  <div>
  </div>
   <h2> {{ title }} </h2>
</template>

3. Composition API

Vue2 and Vue3 The biggest difference - Vue2 uses the options API (Options API) compared to the Vue3 composition API (Composition API)

The old options API is in the code It is divided into different attributes: data, computed attributes, methods, etc. The new synthetic API allows us to use methods (functions) to separate. Compared with the old API that uses attributes to group, this way the code will be simpler and cleaner.

vue2

export default {
  props: {
    title: String
  },
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    login () {
      // 登陆方法
    }
  },
  components:{
            "buttonComponent":btnComponent
        },
  computed:{
	  fullName(){
	    return this.firstName+" "+this.lastName;     
	  }
}
 
}

vue3

export default {
  props: {
    title: String
  },
  
  setup () {
    const state = reactive({ //数据
      username: '',
      password: '',
      lowerCaseUsername: computed(() => state.username.toLowerCase()) //计算属性
    })
     //方法
    const login = () => {
      // 登陆方法
    }
    return { 
      login,
      state
    }
  }
}

4. Create data data

Vue2 - Put the data into the data attribute here

export default {
  props: {
    title: String
  },
  data () {
    return {
      username: '',
      password: ''
    }
  }
}

In Vue3.0, we need to use a new setup() method, This method is triggered when the component is initialized and constructed.

Use the following three steps to create reactive data:

  • Introduce reactive from vue

  • Use the reactive() method to Declare our data as responsive data

  • Use the setup() method to return our responsive data so that our template can obtain these responsive data

import { reactive } from 'vue'

export default {
  props: {
    title: String
  },
  setup () {
    const state = reactive({
      username: '',
      password: ''
    })

    return { state }
  }
}

When template is used, the value of the data can be obtained through state.username and state.password.

<template>
  <div>
    <h2> {{ state.username }} </h2>
  </div>
</template>

5. Lifecycle Hooks—Lifecyle Hooks

Vue2--------------vue3
beforeCreate  -> setup()
created       -> setup()
beforeMount   -> onBeforeMount
mounted       -> onMounted
beforeUpdate  -> onBeforeUpdate
updated       -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed     -> onUnmounted
activated     -> onActivated
deactivated   -> onDeactivated
  • setup(): Before starting to create a component, Executed before beforeCreate and created. What is created is data and method

  • onBeforeMount(): a function executed before the component is mounted on the node.

  • onMounted(): Function executed after the component is mounted.

  • onBeforeUpdate(): Function executed before the component is updated.

  • onUpdated(): Function executed after component update is completed.

  • onBeforeUnmount(): Function executed before the component is unmounted.

  • onUnmounted(): Function executed after component uninstallation is completed

    If the component is included by <keep-alive></keep-alive>, the following two hooks will be available function.
  • onActivated(): The component included will have two more life cycle hook functions. Executed when activated.

  • onDeactivated(): For example, switch from component A to component B, and execute when component A disappears.

6. Parent and son pass different parameters, setup() function characteristics

Summary:

1), When setting up the function, it will accept two parameters: (props, context (including attrs, slots, emit))

2). The setup function is the function before the two hook functions beforeCreate and Created in the life cycle.

3) When executing setup, the component instance has not yet been created (inside setup(), this will not be a reference to the active instance, that is, it does not point to the vue instance. In order to avoid our wrong use, Vue directly Modify this in the setup function to undefined)

4), use it with the template: you need to return an object (variables and methods defined in the setup function need to be returned in the end If it goes out, it cannot be used in the template)

5), use rendering function: you can return a rendering function, which can directly use the responsive state declared in the same scope

Notes:

1), this cannot be used in the setup function. In order to avoid our incorrect use, Vue directly changed this in the setup function to undefined)

2)、setup 函数中的 props 是响应式的,当传入新的 prop 时,它将被更新。但是,因为 props 是响应式的,你不能使用 ES6 解构,因为它会消除 prop 的响应性。

如果需要解构 prop,可以通过使用 setup 函数中的toRefs 来完成此操作:

父传子,props

import { toRefs } from 'vue'
 
setup(props) {
	const { title } = toRefs(props)
 
	console.log(title.value)
	onMounted(() => {
      console.log('title: ' + props.title)
    })

}

子传父,事件 - Emitting Events

举例,现在我们想在点击提交按钮时触发一个login的事件。

在 Vue2 中我们会调用到this.$emit然后传入事件名和参数对象。

login () {
      this.$emit('login', {
        username: this.username,
        password: this.password
      })
 }

在setup()中的第二个参数content对象中就有emit,这个是和this.$emit是一样的。那么我们只要在setup()接收第二个参数中使用分解对象法取出emit就可以在setup方法中随意使用了。

然后我们在login方法中编写登陆事件
另外:context 是一个普通的 JavaScript 对象,也就是说,它不是响应式的,这意味着你可以安全地对 context 使用 ES6 解构

setup (props, { attrs, slots, emit }) {
    // ...
    const login = () => {
      emit('login', {
        username: state.username,
        password: state.password
      })
    }

    // ...
}

3)、 setup()内使用响应式数据时,需要通过.value获取

import { ref } from 'vue'
 
const count = ref(0)
console.log(count.value) // 0

4)、从 setup() 中返回的对象上的 property 返回并可以在模板中被访问时,它将自动展开为内部值。不需要在模板中追加 .value

5)、setup函数只能是同步的不能是异步的

7. vue3 Teleport瞬移组件

Teleport一般被翻译成瞬间移动组件,实际上是不好理解的.我把他理解成"独立组件",
他可以那你写的组件挂载到任何你想挂载的DOM上,所以是很自由很独立的
以一个例子来看:编写一个弹窗组件

<template>
<teleport>
  <div>
    <h2><slot>this is a modal</slot></h2>
    <button>Close</button>
  </div>
</teleport>
</template>
<script>

export default {
  props: {
    isOpen: Boolean,
  },
  emits: {
    &#39;close-modal&#39;: null
  },
  setup(props, context) {
    const buttonClick = () => {
      context.emit(&#39;close-modal&#39;)
    }
    return {
      buttonClick
    }
  }
}
</script>
<style>
  #center {
    width: 200px;
    height: 200px;
    border: 2px solid black;
    background: white;
    position: fixed;
    left: 50%;
    top: 50%;
    margin-left: -100px;
    margin-top: -100px;
  }
</style>

在app.vue中使用的时候跟普通组件调用是一样的

<template>
<div>
  <img  alt="What is the difference between vue2 and vue3" >
  <helloworld></helloworld>
  <hooksdemo></hooksdemo>
  <button>Open Modal</button><br>
<modal> My Modal !!!!</modal>
</div>
  
</template>
<script>
import HelloWorld from &#39;./components/HelloWorld.vue&#39;
import HooksDemo from &#39;./components/HooksDemo.vue&#39;
import Modal from &#39;./components/Modal.vue&#39;
import{ref} from &#39;vue&#39;
export default {
  name: &#39;App&#39;,
  components: {
    HelloWorld,
    HooksDemo,
    Modal
  },
  setup() {
    const modalIsOpen = ref(false)
    const openModal = () => {
      modalIsOpen.value = true
    }
    const onModalClose = () => {
      modalIsOpen.value = false
    }
    return {
      modalIsOpen,
      openModal,
      onModalClose
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

要是在app.vue文件中使用的时候,modal是在app的 DOM节点之下的,父节点的dom结构和css都会给modal产生影响
于是产生的问题

  • modal被包裹在其它组件之中,容易被干扰

  • 样式也在其它组件中,容易变得非常混乱

Teleport 可以把modal组件渲染到任意你想渲染的外部Dom上,不必嵌套在#app中,这样就可以互不干扰了,可以把Teleport看成一个传送门,把你的组件传送到任何地方

使用的时候 to属性可以确定想要挂载的DOM节点下面

<template>
  <teleport>
    <div>
      <h2>柏特better</h2>
    </div>
  </teleport>
</template>

在public文件夹下的index.html中增加一个节点

nbsp;html>

  
    <meta>
    <meta>
    <meta>
    <link>favicon.ico">
    <title></title>
  
  
    <noscript>
      <strong>We're sorry but  doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div></div>
    <div></div>
    <!-- built files will be auto injected -->
  

这样可以看到modal组件就是没有挂载在app下,不再受app组件的影响了

What is the difference between vue2 and vue3

(学习视频分享:web前端入门vue视频教程

The above is the detailed content of What is the difference between vue2 and vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn