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
If you use yarn, Then execute the following commands in turn :
yarn create vite-app <project-name> cd <project-name> yarn yarn dev
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" } }
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
So what advantages and disadvantages did they have before ?
1、Object.defineProperty() There are three main problems :
Object.keys(obj).forEach(key => { Object.defineProperty(obj, key, { // ... }) })
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 ).
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
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')
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 .
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; }
Using responsive objects
<p> Current count The value of is :{{count}}</p> <button @click="count++"> Click to increase count< button>
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 } }
Using responsive objects
<p> Current count The value of is :{{count}}</p> <button @click="count++"> Click to increase count</button>
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() 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)
Stop listening
watchEffect() When used, returns a function , When executing this returned function , Stop listening
const stop = watchEffect(() => { /* ... */ }) // Stop listening stop()
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
// 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) => { /* ... */ })
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]) => { /* ... */ })
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
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') } }
setup() The first argument to the function is props , Component receives props Data can be setup() Function to access .
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) }