New features of vue3

Pierre brothers 2021-08-08 18:05:51
new features vue3 vue


Unconsciously VUE3.0 It's been a long time since it was released .

stay B I watched the teaching video on the station The moment aroused my strong interest in learning .

 https://www.bilibili.com/video/BV1yK4y1M7Fz?p=8&spm_id_from=pageDriver

 

Vue 3 all-new Web Develop build tools Vite

Vite yes Vue It was developed by you Yuxi Web Develop build tools , It's a browser based native ES Module import development server , In the development environment , Use the browser to parse import, On the server side, on-demand compilation returns , Completely skip the concept of packaging , The server is up and running . At the same time, not only to Vue The document provides support , It also supports hot updates , And the speed of hot update will not slow down with the increase of modules . Use in a production environment Rollup pack .

 

Vite It has the following characteristics :

Fast cold start, instant hot module update (HMR,Hot Module Replacement) Real on demand compilation Vite It's launching Vue 3 It was developed when , Currently only supported Vue 3.x, It means with Vue 3 Libraries that are not compatible with Vite Use it together .

And Vue CLI similar ,Vite It's also available npm perhaps yarn To generate the project structure . Choose a directory , Open the command prompt window , Execute the following commands in turn to build the scaffold project , And start the project .

npm init vite-app <project-name>
cd <project-name>
npm install
npm run dev
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

If you use yarn, Then execute the following commands in turn :

yarn create vite-app <project-name>
cd <project-name>
yarn
yarn dev
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

because Vite Using browser native ES Module import function , but IE 11 Does not support ES Module import , Therefore, based on Vite Development projects , The browser cannot be used IE11, Other mainstream browsers support ES Module function .

 

I created a project The structure is as follows

 

You can find ,Vite The directory structure of the generated scaffold project and Vue CLI The generated project directory structure is very similar , It's true , And the development method is basically the same . however Vite The default is the configuration file vite.config.js, instead of vue.config.js.

package.json The contents of the document are as follows :

{
"name": "webapp-vue3",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"vue": "^3.0.4"
},
"devDependencies": {
"vite": "^1.0.0-rc.13",
"@vue/compiler-sfc": "^3.0.4"
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

 

  Here with Vue CLI Different places are here :

"dev": "vite",

"build": "vite build"

 

Experienced a great wave , Basically, it starts in seconds , After changing the code, it is also updated in seconds .

 

 Vue 3 use Proxy The data was hijacked

 

  1. Vue 2.x utilize Object.defineProperty(), And decouple the internal into Observer, Dep, And use Watcher Connected to a
  2. Vue stay 3.x The version was changed to Proxy To implement

So what advantages and disadvantages did they have before ?

1、Object.defineProperty() There are three main problems :

  • Can't listen for array changes
  • Every property of the object must be traversed
  • You have to go deep through nested objects
  • Can't listen for array changes

    These methods of array cannot trigger set Of :push, pop, shift, unshift,splice, sort, reverse.
    Vue Define the method that will modify the original array as the mutation method (mutation method)
    Non mutative method (non-mutating method): for example filter, concat, slice etc. , Neither of them will modify the original array , It will return a new array .
    Vue The approach is to rewrite these methods to implement array hijacking .
  • Every property of the object must be traversed
    Use Object.defineProperty() Most have to cooperate with Object.keys() And traversal ,, So one more layer of nesting

 

 

Object.keys(obj).forEach(key => {
Object.defineProperty(obj, key, {
// ...
})
})
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

 

  You have to go deep through nested objects
When an object is deeply nested , You must traverse layer by layer , Until every property of every object is called Object.defineProperty() until . Vue Such logic in the source code of ----walk Method .

 

2、Proxy:
Proxy Object is used to define the custom behavior of the basic operation ( Such as attribute search , assignment , enumeration , Function calls, etc ).

  • Target : For the entire object , It's not a property of an object
  • Support array : There is no need to overload the methods of the array , Save a lot of hack
  • Nesting supports : get Recursive call inside Proxy And back to
  • other
    Target
    No need. keys Traversal . This solution Object.defineProperty() My second question .Proxy It's about the whole obj Of . therefore obj All contained inside key , You can walk into set.( Save one Object.keys() The traversal )
let obj = {
name: 'Eason',
age: 30
}
let handler = {
get (target, key, receiver) {
console.log('get', key)
return Reflect.get(target, key, receiver)
},
set (target, key, value, receiver) {
console.log('set', key, value)
return Reflect.set(target, key, value, receiver)
}
}
let proxy = new Proxy(obj, handler)
proxy.name = 'Zoe' // set name Zoe
proxy.age = 18 // set age 18
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

 

in addition Reflect.get and Reflect.set It can be understood as... In class inheritance super, That is, call the original method

 

 

 

Nesting supports
Proxy Nesting is also not supported , This and Object.defineProperty() It's the same . Therefore, it also needs to be solved by layer by layer traversal .Proxy It's written in get Recursive call inside Proxy And back to

let obj = {
info: {
name: 'eason',
blogs: ['webpack', 'babel', 'cache']
}
}
let handler = {
get (target, key, receiver) {
console.log('get', key)
// Recursively create and return
if (typeof target[key] === 'object' && target[key] !== null) {
return new Proxy(target[key], handler)
}
return Reflect.get(target, key, receiver)
},
set (target, key, value, receiver) {
console.log('set', key, value)
return Reflect.set(target, key, value, receiver)
}
}
let proxy = new Proxy(obj, handler)
// The following two sentences can enter set
proxy.info.name = 'Zoe'
proxy.info.blogs.push('proxy')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

 

Other aspects

    advantage :Proxy The second parameter of can have 13 Interception methods , Than Object.defineProperty() To be richer ,Proxy As a new standard, it has attracted the attention and performance optimization of browser manufacturers , by comparison Object.defineProperty() It's an old method .
    Inferiority :Proxy The compatibility is not as good as Object.defineProperty() (caniuse The data shows that ,QQ Browser and Baidu browser do not support Proxy, This is estimated to be unacceptable for domestic mobile development , But both support Object.defineProperty()), Out of commission polyfill To handle compatibility

 

 

 Vue 3 use Proxy The data was hijacked

 

Vue3 New features ( Two ) —— Composition-Api

Composition API : A set of low intrusive 、 Functional API, It gives us more flexibility to 「 Combine 」 Logic of components .

 

Composition API My inspiration comes from React Hooks , It's better than mixin A stronger existence . It can improve the reusability of code logic , So as to realize the independence with the template ; At the same time, functional programming makes the code more compressible . in addition , hold Reactivity Separate modules , signify Vue3.0 Responsive modules can be combined with other frameworks .

 

 

 

  Pictured above , In writing larger components , Composition-Api You can make the logic of complex components more compact , And common logic can be extracted .

1. reactive()

reactive() Function receives a normal object , Returns a responsive object .

stay Vue2.x In the version of the , All we need to do is data() Define a data in to turn it into responsive data , stay Vue3.0 in , Need to use reactive Function or ref To create responsive data .

setup() {
// Create responsive objects
const state = reactive({
count:0
});
// The responsive object return get out , Exposed to template use
return state;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

 

Using responsive objects

<p> Current count The value of is :{{count}}</p>
<button @click="count++"> Click to increase count< button>
  • 1.
  • 2.
  • 3.

 

 

2. ref()

ref() Function can create a responsive data object based on a given value , The return value is an object , And only one .value attribute .

  • use ref Create responsive objects

setup() {
// Create responsive objects
const count = ref(0);
return {
count
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

 

Using responsive objects

<p> Current count The value of is :{{count}}</p>
<button @click="count++"> Click to increase count</button>
  • 1.
  • 2.
  • 3.

 

ref Precautions for

    stay setup() Within the function , from ref() The created responsive data returns an object , So we need to use .value To visit ;

    And in the setup() Outside the function, you don't need .value , Just visit directly .

    Can be in reactive Object ref() Function creates responsive data .

    new ref() Will overwrite the old ref() .

watchEffect()

watchEffect() The incoming function is executed immediately , And listen for its dependencies responsively , And rerun the function when its dependency changes .

const count = ref(0)
// First direct execution , Print out 0
watchEffect(() => console.log(count.value))
setTimeout(() => {
// The data being intercepted changes , The trigger function prints out 1
count.value++
}, 1000)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

 

Stop listening

watchEffect() When used, returns a function , When executing this returned function , Stop listening

const stop = watchEffect(() => {
/* ... */
})
// Stop listening
stop()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

 

watch()

composition-api Medium watch and Vue2.x It's the same in ,watch Need to listen for data , And execute its listening callback . By default, the first render does not execute .

  • watch And watchEffect Different

    1. watch The first rendering does not execute
    2. watch Listen more specifically
    3. watch You can access the values before and after the listening data changes
// Listen for one getter
const state = reactive({ count: 0 })
watch(
() => state.count,
(count, prevCount) => {
/* ... */
}
)
// Listen directly to a ref
const count = ref(0)
watch(count, (count, prevCount) => {
/* ... */
})
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

 

watch Listen to multiple data sources

When listening to multiple data sources , Give the parameters as an array watch

watch([ref1, ref2], ([newRef1, newRef2], [prevRef1, prevRef2]) => {
/* ... */
})
  • 1.
  • 2.
  • 3.

 

 

 

 

 

 

setup() function

I'm learning Composition-Api Before , We need to know setup() function . setup() yes Vue3 What's new in . It is based on Composition API New features provide a unified entry .

stay Vue3 in , Definition methods、watch、computed、data data And so on setup() Function

Be careful : stay setup() Cannot access... In function Vue Of this example

1. Execution opportunity

setup() The function will be in the created() Execute before the lifecycle .

import { ref } from "vue";
// setup stay init Executive
export default {
name: 'HelloWorld',
setup () {
console.log('setup')
const name = ref(' ah sir')
// onMounted(()=>{
// alert('1111')
// })
return {
name
}
},
mounted () {
console.log('mounted')
},
beforeCreate () {
console.log('beforeCreate')
},
created () {
console.log('created')
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

 

 

 

 

 2. receive props data ( because setup No, this, Therefore, access to internal properties can only pass parameters )

 setup() The first argument to the function is props , Component receives props Data can be setup() Function to access .

3. context Context object

context yes setup() Second parameter of , It is a context object , Can pass context To visit Vue Example this .

setup(props,context) {
console.log(this)
console.log(context)
}
  • 1.
  • 2.
  • 3.
  • 4.

 

版权声明
本文为[Pierre brothers]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/08/20210808180206829x.html

  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless