Home  >  Article  >  Web Front-end  >  Vue3.0 new features and usage summary (organized and shared)

Vue3.0 new features and usage summary (organized and shared)

WBOY
WBOYforward
2022-01-28 16:50:523721browse

This article will share with you the new features and usage summary of vue3.0. It includes some new changes and which previous syntax can no longer be used. I hope it will be helpful to everyone.

Vue3.0 new features and usage summary (organized and shared)

1. New changes brought by Vue3

  • Performance improvement (zero cost: you can enjoy it by switching from vue2 to vue3)

    Faster first rendering, faster diff algorithm, less memory usage, smaller packaging size,....

  • Better Typescript support (in vue It is more convenient to write TS below)

  • Provides a new way to write code: Composition API

2. These Vue2.0 The syntax can no longer be used

vue3.0 is compatible with most of the syntax of version 2.0 (how it was written before, it is written normally now), but there are also some destructive syntax updates , please pay special attention to this:

1. Removed the $on method on the vue instance (eventBusVue.prototype.$eventBus=new Vue(); this.$on('event name' , callback)The existing implementation mode is no longer supported and can be replaced by a third-party plug-in). The following is the usage of eventBus in vue2:

Vue.prototype.$eventBus = new Vue()
组件1
this.$on('事件名', 回调)
组件2
this.$emit('事件名')

2. Remove the filter option. The following is the usage of filters in vue2:

<div>{{ msg | format}}</div>
插值表达式里, 不能再使用过滤器filter, 可以使用methods替代
{{format(msg)}}

3. Remove the .sync syntax (the .sync modifier cannot be used in v-bind, and now it is merged with the v-model syntax). The following is the usage of .sync in vue2

<el-dialog :visibel.sync="showDialog"/>

3, the difference between vue2 and 3 projects

mainly depends on three locations:

  • package.json

  • main.js

  • app.vue

package.json

First we can take a look at the package.json file, which is shown in the dependencies configuration item. The version we are currently using is 3

"dependencies": {
    "core-js": "^3.6.5",
    "vue": "^3.2.25"  // 版本号
}

main.js

then openmain.js Entry file, it is found that the instantiation of Vue has undergone some changes, from the previous new keyword instantiation to the call form of the createApp method.

Writing in vue2.x:

import Vue from 'vue'
import App from './App.vue'
new Vue({render: h => h(App)}).$mount('#app')

Writing in vue3.x:

import { createApp } from 'vue'
import App from './App.vue' // 根组件
createApp(App).mount('#app')

app.vue

Open app.vue and find: vue3. It is no longer mandatory to have a unique root element in 0's single file component

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js App"/>
</template>

4. Combination API and option API

Composition API (Composition API) is vue3's most important factor for our developers This is a very big update.

Vue2 options API, options API (pictured), Vue3 combined API, composition API (pictured on the right):

                                 

Vue2 option API, options API:

Advantages:

Easy to understand and easy to use. Because each option (configuration item) has a fixed writing position (for example, the data is written in the data option, the operation method is written in methods, etc.)

Disadvantages:

The application is large After that, I believe everyone has encountered the dilemma of going back and forth to find the code-----jumping horizontally.

Vue3 composition API, composition API:

Features:

  • Everything related to specific functions is put together Maintenance, such as the responsive data related to function A, methods of operating data, etc. are put together, so that no matter how big the application is, all related codes of a certain function can be quickly located, and maintenance is easy to set up

  • If the function is complex and the amount of code is large, we can also perform logical split processing.

##                          

Summary:

The origin of the combined API. Since vue3 provides a new way of writing code (the old way can also be used), in order to distinguish vue2, they are given different names:

Vue2 option API (option api) Advantages: Simple, each option performs its own function; Disadvantages: Inconvenient for function reuse; Function code is scattered and maintained, and code jumps

Vue3 composition API (composition api) Advantages: Function code combination maintenance, convenient for function reuse;

4. setup

  • The setup function is a new component option, which serves as the starting point (entry) of the combined API in the component

  • This cannot be used in setup, this points to undefined

  • The setup function will only be executed once when the component is initialized

  • The setup function is executed before the beforeCreate life cycle hook is executed

setup() {
	console.log('setup....', this)
},
beforeCreate() {
	console.log('beforeCreate') // 它比setup迟
}

setup parameters:

When using setup, it accepts two parameters :

  • props: props is an object, which contains all the prop data passed by the parent component

  • context: context对象包含了attrs,slots, emit属性

返回值

这个函数的返回值是一个对象,在模版中需要使用的数据和函数,需要在这个对象中声明(如果在data()中也定义了同名的数据,则以setup()中为准)。

<template>
  <div class="container">
    姓名:{{name}},月薪:{{salary}} <button @click="say">打个招呼</button>
  </div>
</template>
<script>
export default {
  setup () {
    console.log('setup执行了,这里没有this. this的值是:', this)
 
    // 定义数据和函数
    const name = '小吴'
    const salary = 18000
    const say = () => {
      console.log('我是', name)
    }
 
    // 返回对象,给视图使用
    return { msg , say}
  },
  beforeCreate() {
    console.log('beforeCreate执行了, 这里有this,this的值是:',  this)
  }
}
</script>

setup 中接受的props是响应式的, 当传入新的 props 时,会及时被更新。由于是响应式的, 所以不可以使用 ES6 解构,解构会消除它的响应式。 错误代码示例, 这段代码会让 props 不再支持响应式:

export default com ({
    setup(props, context) {
        const { uname } = props
        console.log(uname)
    },
})

开发中我们想要使用解构,还能保持props的响应式,有没有办法解决呢?setup接受的第二个参数context,我们前面说了setup中不能访问 Vue2 中最常用的this对象,所以context中就提供了this中最常用的三个属性:attrs、slot 和emit,分别对应 Vue2.x 中的 $attrs属性、slot 插槽 和$emit发射事件。并且这几个属性都是自动同步最新的值,所以我们每次使用拿到的都是最新值。

5、reactive、ref 与 toRefs

在 vue2.x 中, 定义数据都是在data中, 但是 Vue3.x 可以使用 reactive 和 ref 来进行数据定义。

如何取舍ref和reactive?

定义响应式数据有两种方式:

  • ref函数(可以处理简单数据,也可以处理复杂数据),常用于将简单数据类型定义为响应式数据

    • 在代码中修改(或者获取)值时,需要补上.value

    • 在模板中使用时,可以省略.value

  • reactive函数,常用于将复杂数据类型为响应式数据

推荐用法:

  • 优先使用ref

  • 如果明确知道对象中有什么属性,就使用reactive。例如,表单数据

接下来使用代码展示一下 ref、reactive的使用:

<template>
  <div class="container">
    <p>{{ num }}</p>
    <p>姓名: {{ user.uname }}</p>
    <p>年龄: {{ user.age }}</p>
  </div>
</template>
 
<script>
import { reactive, ref, toRefs } from "vue";
export default com({
  setup() {
    const num = ref(0);
    const user = reactive({ uname: "vivian", age: 18});
    setInterval(() => {
      num.value++;
      user.age++;
    }, 1000);
    return {
      year,
      user
    };
  },
});
</script>

上面的代码中,我们绑定到页面是通过user.uname,user.age这样写感觉很繁琐,我们能不能直接将user中的属性解构出来使用呢? 答案是不能直接对user进行结构,这样会消除它的响应式,这里就和上面我们说props不能使用 ES6 直接解构就呼应上了。那我们就想使用解构后的数据怎么办,解决办法就是使用toRefs,定义转换响应式中所有属性为响应式数据,通常用于解构|展开reactive定义对象, 简化我们在模板中的使用。

格式:

// 响应式数据:{ 属性1, 属性2 }
let { 属性1, 属性2 } = toRefs(响应式数据)

具体使用方式如下:

<template>
  <div class="container">
    <p>{{ num }}</p>
    <p>姓名: {{ uname }}</p>
    <p>年龄: {{ age }}</p>
  </div>
</template>
 
<script>
import { defineComponent, reactive, ref, toRefs } from "vue";
export default com({
  setup() {
    const num = ref(0);
    const user = reactive({ uname: "vivian", age: 18});
    setInterval(() => {
      num.value++;
      user.age++;
    }, 1000);
    return {
      year,
      // 使用reRefs
      ...toRefs(user),
    };
  },
});
</script>

增强版的结构赋值:在解构对象的同时,保留响应式的特点。  

6、vue3.0生命周期钩子函数

  •  setup创建实例前

  • onBeforeMount挂载DOM前

  • onMount挂载DOM后

  • BeforeUpdate 更新组件前

  • updated 更新组件后

  • onBeforeUnmount卸载销毁前

  • onUnmount 卸载销毁后

setup () {
    onBeforeMount(()=>{
      console.log('DOM渲染前',document.querySelector('.container'))
    })
    onMounted(()=>{
      console.log('DOM渲染后1',document.querySelector('.container'))
    })
  }

 Vue3.x 还新增用于调试的钩子函数onRenderTriggered和onRenderTricked,  另外,Vue3.x 中的钩子是需要从 vue 中导入的:

import { defineComponent, onBeforeMount, onMounted, onBeforeUpdate,onUpdated,
onBeforeUnmount, onUnmounted, onErrorCaptured, onRenderTracked,onRenderTriggered } from "vue"; 
export default defineComponent({ 
//beforeCreate和created是vue2的 
beforeCreate() {
console.log("--beforeCreate--")
 }, 
created() {
console.log("--created--")
 }, 
setup() { 
console.log("--setup--")
// vue3.x生命周期写在setup中 
onBeforeMount(() => {
console.log("--onBeforeMount--")
})
onMounted(() => {
console.log("--onMounted--"); })
 // 调试哪些数据发生了变化
onRenderTriggered((event) =>{ 
console.log("--onRenderTriggered--",event)
}) 
}, 
});

7、computed函数定义计算属性

格式: 

import { computed } from 'vue'
 
const 计算属性名 = computed(() => {
  return 相关计算结果
})

代码示例:

<template>
  <p>姓名:{{name}}, 公司:{{company}}, 月薪:{{salary}}, 年薪{{total}}</p>
  <button @click="double">月薪double</button>
</template>
<script>
import { ref, computed } from 'vue'
export default {
  name: 'App',
  setup () {
    // 定义响应式对象
    const company = ref('DiDi')
    const name = ref('小王')
    const salary = ref(18000)
    const double = () => {
      salary.value *= 2 // ref数据要加.value
    }
    // 定义计算属性
    const total = computed(() => 12 * salary.value)
    
    return {  
      name, 
      company,
      total,
      salary,
      double
    }
  }
}
</script>

总结:

vue3中的computed函数与vue2中的computed选项功能类似。

computed的入参是一个函数

作用:根据已有数据,产生新的响应式数据。

步骤:导入,定义,导出

computed的高级用法:

格式:

const 计算属性 =  computed({
  get () {
    // 当获取值自动调用
  },
  set (val) {
    // 当设置值自动调用,val会自动传入
  }
})

 示例代码:

<template>
  <div style="padding:2em">
    <p>小花, 月薪:{{salary}}, 年薪:{{total}}</p>
    <p>年薪:<input v-model="total"/></p>
    <button @click="double">月薪double</button>
  </div>
</template>
<script>
// reactive: 是除了ref之外的第二种申明响应式数据的方式
 
import { ref, computed } from 'vue'
export default {
  setup () {
  
    const salary = ref(18000)
     
    const double = () => {
      salary.value *= 2
      console.log(salary)
    }
    // 定义计算属性: 普通的写法:只使用了get
    // const total = computed(() => {
    //   return stu.salary * 12
    // })
 
    // 定义计算属性: 高阶的写法:使用了get + set
    const total = computed({
      get() { return salary.value * 12 },
      set(val) { 
        // 设置计算属性的值,会自动调用,并传入val
        console.log('要设置的值...', val)
        salary.value = val/12
      }
    })
    
    return { double, salary, total}
  }
}
</script>

总结:

计算属性两种用法

  • 给computed传入函数,返回值就是计算属性的值

  • 给computed传入对象,get获取计算属性的值,set监听计算属性改变

  • 在v-model绑定计算属性: <input v-model="total" />

8、watch函数

基于响应式数据的变化执行回调逻辑,和vue2中的watch的应用场景完全一致。

步骤: 

  • 导入 import { watch } from 'vue'

  • 开启监听。在setup函数中执行watch函数开启对响应式数据的监听

  • watch函数接收三个常规参数  watch(source, callback, [options])

    • 第一个参数有三种取值:

      对象,要监听的响应式数据

      数组,每个元素是响应式数据

      函数,返回你要监听变化的响应式数据

    • 第二个参数是:响应式数据变化之后要执行的回调函数

    • 第三个参数是: 一个对象,在里面配置是否开启立刻执行或者深度监听

<template>
    <div>
        {{stu}}, {{salary}}
        <button @click="doSome"> do</button>
    </div>
</template>
<script>
import { reactive, watch, ref } from 'vue'
export default {
    setup() {
        const salary = ref(10000)
        const stu  = reactive({
            address: {city: 'wuhan'}
        })
 
        // 1. 侦听-单个数据
        watch(salary, (newVal, oldVal) => {
            console.log('监听单个数据', newVal, oldVal)
        })
			// 侦听-单个数据
        watch(stu, (newVal, oldVal) => {
            console.log('监听单个数据', newVal, oldVal)
        })
 
      	// 侦听-多个数据
        watch([stu, salary], (newVal, oldVal) => {
            console.log('监听多个数据', newVal, oldVal)
        })
				// 侦听对象的某个属性
        watch(()=>stu.address , (newVal, oldVal) => {
            console.log('第一个参数是函数', newVal, oldVal)
        }, {deep: true,  immediate: true} )
 
        // 测试按钮,修改数据
        const doSome = () => {
            salary.value +=1
            stu.address.city = ''
        }
 
        return {stu, salary, doSome}
    }
}
</script>

总结:

作用:watch用来侦听数据的变化。

格式:watch(数据|数组|get函数,(新值,旧值)=>{回调处理逻辑}, {immediate:true|false, deep: true|false})

以上,我们了解了vue2和vue3使用方法的不同,关于组件通讯和插槽等可以看下一篇。

【相关推荐:《vue.js教程》】

The above is the detailed content of Vue3.0 new features and usage summary (organized and shared). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete