当前位置:网站首页>New features of vue3
New features of vue3
2020-11-06 22:11:00 【The front end of the attack】
Crack vue3.x New characteristics
Video address
https://www.bilibili.com/video/av69262619/
0. Basic requirements
-
Learn about common ES6 New characteristics
-
ES6 Import and export syntax of
-
Deconstruct assignment
-
Arrow function
-
etc…
-
-
understand vue 2.x Basic use of
-
Components
-
Common instructions
-
Life cycle function
-
computed、watch、ref etc.
-
1. Related resources
-
【 You know - Vue Function-based API RFC】https://zhuanlan.zhihu.com/p/68477600
-
【github - vuejs/composition-api】https://github.com/vuejs/composition-api
-
【github - composition-api/CHANGELOG.md】https://github.com/vuejs/composition-api/blob/master/CHANGELOG.md
-
【 Open source in China - Yuxi announced Vue 3.0 Development route : Will rewrite... From scratch 3.0】https://www.oschina.net/news/100515/plans-for-the-next-iteration-of-vue-js
2. Initialize project
-
install vue-cli3
npm install -g @vue/cli # OR yarn global add @vue/cli
-
Create project
vue create my-project # OR vue ui
-
Install... In the project
composition-api
Experience vue3 New characteristicsnpm install @vue/composition-api --save # OR yarn add @vue/composition-api
-
In use of any
@vue/composition-api
Before the ability to provide , Must pass firstVue.use()
Installationimport Vue from 'vue' import VueCompositionApi from '@vue/composition-api' Vue.use(VueCompositionApi)
After installing the plug-in , You can use the new Composition API To develop components .
3. setup
setup()
The function is vue3 in , New properties for components . It's for us to use vue3 Of Composition API
New features provide a unified entry point .
3.1 Execution opportunity
setup The function will be in the beforeCreate after 、created Before execution
3.2 receive props data
-
stay
props
Defines the parameter names that the current component allows external passing :props: { p1: String }
-
adopt
setup
Functional First parameter , receiveprops
data :setup(props) { console.log(props.p1) }
3.3 context
setup
The second parameter of a function is a Context object , This context object contains some useful properties , These attributes are in vue 2.x
We need to go through this
To access , stay vue 3.x
in , They are accessed as follows :
const MyComponent = {
setup(props, context) {
context.attrs
context.slots
context.parent
context.root
context.emit
context.refs
}
}
Be careful : stay
setup()
Cannot access... In functionthis
4. reactive
reactive()
Function to receive a normal object , Returns a responsive data object .
4.1 Basic grammar
Equivalent to vue 2.x
Medium Vue.observable()
function ,vue 3.x
Provided in reactive()
function , Used to create responsive data objects , The basic code example is as follows :
import {
reactive } from '@vue/composition-api'
// Create responsive data objects , Got state Be similar to vue 2.x in data() Response object returned
const state = reactive({
count: 0 })
4.2 Define responsive data for template Use
-
Import on demand
reactive
function :import { reactive } from '@vue/composition-api'
-
stay
setup()
Call in functionreactive()
function , Create responsive data objects :setup() { // Create responsive data objects const state = reactive({ count: 0}) // setup Function will respond to the data object return get out , for template Use return state }
-
stay
template
Access to responsive data :<p> Current count The value is :{ {count}}</p>
5. ref
5.1 Basic grammar
ref()
Function to create a... Based on a given value Response type Of Data objects ,ref()
The return value of a function call is an object , This object contains only one .value
attribute :
import {
ref } from '@vue/composition-api'
// Create responsive data objects count, The initial value is 0
const count = ref(0)
// If you want to access ref() The value of the created responsive data object , Must pass .value Property is OK
console.log(count.value) // Output 0
// Give Way count Value +1
count.value++
// Print again count Value
console.log(count.value) // Output 1
5.2 stay template Medium visit ref Create responsive data
-
stay
setup()
Create responsive data in :import { ref } from '@vue/composition-api' setup() { const count = ref(0) return { count, name: ref('zs') } }
-
stay
template
Access to responsive data :<template> <p>{ {count}} --- { {name}}</p> </template>
5.3 stay reactive Object ref Create responsive data
When put ref()
Created responsive data objects , Mount to reactive()
Upper time , Will automatically put the response data object Expand to original value , No need to pass .value
Can be accessed directly , for example :
const count = ref(0)
const state = reactive({
count
})
console.log(state.count) // Output 0
state.count++ // There is no need to pass .value You can access the original values directly
console.log(count) // Output 1
Be careful : new ref Will overwrite the old ref, The sample code is as follows :
// establish ref And mount reactive in
const c1 = ref(0)
const state = reactive({
c1
})
// Create again ref, Name it c2
const c2 = ref(9)
// take used ref c1 Replace with new ref c2
state.c1 = c2
state.c1++
console.log(state.c1) // Output 10
console.log(c2.value) // Output 10
console.log(c1.value) // Output 0
6. isRef
isRef()
Used to determine whether a value is ref()
Created objects ; Application scenarios : When you need to expand a certain possibility for ref()
When creating the value , for example :
import {
isRef } from '@vue/composition-api'
const unwrapped = isRef(foo) ? foo.value : foo
7. toRefs
toRefs()
The function can change reactive()
Created responsive objects , Convert to a normal object , It's just , Every attribute node on this object , All are ref()
Type of responsive data , The most common application scenarios are as follows :
import {
toRefs } from '@vue/composition-api'
setup() {
// Define responsive data objects
const state = reactive({
count: 0
})
// Define the event handlers available on the page
const increment = () => {
state.count++
}
// stay setup Returns an object for the page to use
// This object can contain responsive data , You can also include event handlers
return {
// take state Every attribute on , All converted to ref Form of responsive data
...toRefs(state),
// Self increasing event handler
increment
}
}
The page can be accessed directly setup()
in return Out of the responsive data :
<template>
<div>
<p> Current count The value is :{
{count}}</p>
<button @click="increment">+1</button>
</div>
</template>
8. computed
computed()
Used to create calculated properties ,computed()
The return value of the function is a ref
Example . Use computed
Before you need to import... On demand :
import {
computed } from '@vue/composition-api'
8.1 Create a read-only calculated property
Calling computed()
During function , Pass in a function
function , You can get a read-only calculated property , The sample code is as follows :
// Create a ref Responsive data
const count = ref(1)
// according to count Value , Create a responsive calculated property plusOne
// It will depend on ref Automatically calculates and returns a new ref
const plusOne = computed(() => count.value + 1)
console.log(plusOne.value) // Output 2
plusOne.value++ // error
8.2 Create readable and writable calculation properties
Calling computed()
During function , Pass in a containing get
and set
Object of function , You can get a readable and writable calculation property , The sample code is as follows :
// Create a ref Responsive data
const count = ref(1)
// Create a computed Compute properties
const plusOne = computed({
// Value function
get: () => count.value + 1,
// The mutator
set: val => {
count.value = val - 1
}
})
// The operation of assigning values to calculated properties , Will trigger set function
plusOne.value = 9
// Trigger set After the function ,count The value of will be updated
console.log(count.value) // Output 8
9. watch
watch()
Function is used to monitor the change of some data items , This triggers certain actions , Need to import on demand before using :
import {
watch } from '@vue/composition-api'
9.1 Basic usage
const count = ref(0)
// Definition watch, as long as count Value change , It will trigger watch Callback
// watch Will be automatically called once at creation time
watch(() => console.log(count.value))
// Output 0
setTimeout(() => {
count.value++
// Output 1
}, 1000)
9.2 Monitor the specified data source
monitor reactive
Data source of type :
// Define data sources
const state = reactive({
count: 0 })
// monitor state.count The change of this data node
watch(
() => state.count,
(count, prevCount) => {
/* ... */
}
)
monitor ref
Data source of type :
// Define data sources
const count = ref(0)
// Specify the data source to monitor
watch(count, (count, prevCount) => {
/* ... */
})
9.3 Monitoring multiple data sources
monitor reactive
Data source of type :
const state = reactive({
count: 0, name: 'zs' })
watch(
[() => state.count, () => state.name], // Object.values(toRefs(state)),
([count, name], [prevCount, prevName]) => {
console.log(count) // new count value
console.log(name) // new name value
console.log('------------')
console.log(prevCount) // old count value
console.log(prevName) // new name value
},
{
lazy: true // stay watch When created , Do not execute the code in the callback function
}
)
setTimeout(() => {
state.count++
state.name = 'ls'
}, 1000)
monitor ref
Data source of type :
const count = ref(0)
const name = ref('zs')
watch(
[count, name], // Many that need to be monitored ref data source
([count, name], [prevCount, prevName]) => {
console.log(count)
console.log(name)
console.log('-------------')
console.log(prevCount)
console.log(prevName)
},
{
lazy: true
}
)
setTimeout(() => {
count.value++
name.value = 'xiaomaolv'
}, 1000)
9.4 Clear surveillance
stay setup()
Function watch
monitor , It will automatically stop when the current component is destroyed . If you want to explicitly stop a surveillance , You can call watch()
The return value of the function is just , The grammar is as follows :
// Create a monitor , And get the Stop function
const stop = watch(() => {
/* ... */
})
// Call stop function , Clear the corresponding monitor
stop()
9.5 stay watch Clear invalid asynchronous tasks
occasionally , When watch
When the monitored value changes , or watch
By itself stop
after , We expect to be able to clean up those invalid asynchronous tasks , here ,watch
A callback function is provided cleanup registrator function
To carry out the cleanup . This cleanup function will be called in the following cases :
- watch It's repeated
- watch Forced
stop
了
Template The code example in is as follows :
/* template The code in */ <input type="text" v-model="keywords" />
Script The code example in is as follows :
// Define responsive data keywords
const keywords = ref('')
// Asynchronous task : Print keywords entered by users
const asyncPrint = val => {
// Time delay 1 Print in seconds
return setTimeout(() => {
console.log(val)
}, 1000)
}
// Definition watch monitor
watch(
keywords,
(keywords, prevKeywords, onCleanup) => {
// Perform asynchronous tasks , And get to close the asynchronous task timerId
const timerId = asyncPrint(keywords)
// If watch Monitoring is repeated , The last outstanding asynchronous task will be cleared first
onCleanup(() => clearTimeout(timerId))
},
// watch It is not executed when it is first created
{
lazy: true }
)
// hold template Data needed in return get out
return {
keywords
}
10. LifeCycle Hooks
New life cycle functions , It can be imported into components on demand , And only in setup()
Use in a function , The code example is as follows :
import {
onMounted, onUpdated, onUnmounted } from '@vue/composition-api'
const MyComponent = {
setup() {
onMounted(() => {
console.log('mounted!')
})
onUpdated(() => {
console.log('updated!')
})
onUnmounted(() => {
console.log('unmounted!')
})
}
}
The following list , yes vue 2.x Life cycle function and new version Composition API Mapping between :
beforeCreate
-> usesetup()
created
-> usesetup()
beforeMount
->onBeforeMount
mounted
->onMounted
beforeUpdate
->onBeforeUpdate
updated
->onUpdated
beforeDestroy
->onBeforeUnmount
destroyed
->onUnmounted
errorCaptured
->onErrorCaptured
11. provide & inject
provide()
and inject()
Data transfer between nested components can be realized . These two functions can only be used in setup()
Use in a function . Use... In parent components provide()
Function to pass data down ; Use... In child components inject()
Get the data from the upper layer .
11.1 Share common data
App.vue
The root component :
<template>
<div id="app">
<h1>App The root component </h1>
<hr />
<LevelOne />
</div>
</template>
<script>
import LevelOne from './components/LevelOne'
// 1. Import on demand provide
import { provide } from '@vue/composition-api'
export default {
name: 'app',
setup() {
// 2. App The root component is the parent component , adopt provide Function to share data with child components ( No hierarchy )
// provide(' The name of the data to share ', Shared data )
provide('globalColor', 'red')
},
components: {
LevelOne
}
}
</script>
LevelOne.vue
Components :
<template>
<div>
<!-- 4. Bind by attributes , Set the font color for the label -->
<h3 :style="{color: themeColor}">Level One</h3>
<hr />
<LevelTwo />
</div>
</template>
<script>
import LevelTwo from './LevelTwo'
// 1. Import on demand inject
import { inject } from '@vue/composition-api'
export default {
setup() {
// 2. call inject Function time , By specifying the data name , Get the data shared by the parent
const themeColor = inject('globalColor')
// 3. Put the received shared data return to Template Use
return {
themeColor
}
},
components: {
LevelTwo
}
}
</script>
LevelTwo.vue
Components :
<template>
<div>
<!-- 4. Bind by attributes , Set the font color for the label -->
<h5 :style="{color: themeColor}">Level Two</h5>
</div>
</template>
<script>
// 1. Import on demand inject
import { inject } from '@vue/composition-api'
export default {
setup() {
// 2. call inject Function time , By specifying the data name , Get the data shared by the parent
const themeColor = inject('globalColor')
// 3. Put the received shared data return to Template Use
return {
themeColor
}
}
}
</script>
11.2 share ref Responsive data
The following code realizes the function of switching theme colors by clicking buttons , Major modifications App.vue
Code in component ,LevelOne.vue
and LevelTwo.vue
The code in is not subject to any changes :
<template>
<div id="app">
<h1>App The root component </h1>
<!-- Click on App.vue Button in , Toggle the color of the text in the subcomponent -->
<button @click="themeColor='red'"> Red </button>
<button @click="themeColor='blue'"> Blue </button>
<button @click="themeColor='orange'"> Orange </button>
<hr />
<LevelOne />
</div>
</template>
<script>
import LevelOne from './components/LevelOne'
import { provide, ref } from '@vue/composition-api'
export default {
name: 'app',
setup() {
// Definition ref Responsive data
const themeColor = ref('red')
// hold ref Data is passed through provide The supplied subcomponent uses
provide('globalColor', themeColor)
// setup in return Data for current component Template Use
return {
themeColor
}
},
components: {
LevelOne
}
}
</script>
12. template refs
adopt ref()
You can also reference elements or components on a page .
12.1 Reference to element
The sample code is as follows :
<template>
<div>
<h3 ref="h3Ref">TemplateRefOne</h3>
</div>
</template>
<script>
import { ref, onMounted } from '@vue/composition-api'
export default {
setup() {
// Create a DOM quote
const h3Ref = ref(null)
// stay DOM After the first load , To get a reference to an element
onMounted(() => {
// by dom Element set font color
// h3Ref.value It's original DOM object
h3Ref.value.style.color = 'red'
})
// Put the created reference return get out
return {
h3Ref
}
}
}
</script>
12.2 References to components
TemplateRefOne.vue
The sample code in is as follows :
<template>
<div>
<h3>TemplateRefOne</h3>
<!-- 4. Click the button to display the count value -->
<button @click="showNumber"> obtain TemplateRefTwo Medium count value </button>
<hr />
<!-- 3. Add... To the component ref quote -->
<TemplateRefTwo ref="comRef" />
</div>
</template>
<script>
import { ref } from '@vue/composition-api'
import TemplateRefTwo from './TemplateRefTwo'
export default {
setup() {
// 1. Create a component of ref quote
const comRef = ref(null)
// 5. In the presentation subcomponent count Value
const showNumber = () => {
console.log(comRef.value.count)
}
// 2. Put the created reference return get out
return {
comRef,
showNumber
}
},
components: {
TemplateRefTwo
}
}
</script>
TemplateRefTwo.vue
Sample code in :
<template>
<div>
<h5>TemplateRefTwo --- {
{count}}</h5>
<!-- 3. Click button , Give Way count Value on the +1 -->
<button @click="count+=1">+1</button>
</div>
</template>
<script>
import { ref } from '@vue/composition-api'
export default {
setup() {
// 1. Define responsive data
const count = ref(0)
// 2. Put responsive data return to Template Use
return {
count
}
}
}
</script>
13. createComponent
This function is not necessary , Unless you want the perfect combination TypeScript Provide type inference for project development .
This function only provides type inference , Convenience is in combination with TypeScript When writing code , for setup()
Medium props
Provide complete type inference .
import {
createComponent } from 'vue'
export default createComponent({
props: {
foo: String
},
setup(props) {
props.foo // <- type: string
}
})
版权声明
本文为[The front end of the attack]所创,转载请带上原文链接,感谢
边栏推荐
- September 3, 2020: naked writing algorithm: loop matrix traversal.
- Configuration of AP hotspot on xunwei-imx6ull development board
- 移动端像素适配方案
- STM32F030C6T6兼容替换MM32SPIN05PF
- vue3 新特性
- Qt音视频开发46-视频传输UDP版
- Application insights application insights use application maps to build request link views
- File download manager realized by electron
- Interviewer: how about shardingsphere
- Erd-online free online database modeling tool
猜你喜欢
image operating system windows cannot be used on this platform
汽车维修app开发的好处与功能
小程序商城系统插件代码该如何写?怎么用代码检查添加插件是否成功?
This project allows you to quickly learn about a programming language in a few minutes
Unexpected element.. required element
What the hell is fastthreadlocal? The existence of ThreadLocal!!
心理咨询app开发所具备的优点与功能
STM32F030K6T6兼容替换灵动MM32F031K6T6
September 3, 2020: naked writing algorithm: loop matrix traversal.
[doodling the footprints of Internet of things] Introduction to Internet of things
随机推荐
C and C / C + + mixed programming series 5 - GC collaboration of memory management
Method of code refactoring -- Analysis of method refactoring
2020年新规,微信封号怎么快速解除?
Common syntax corresponding table of mongodb and SQL
Js字符串-String字符串对象方法
20个XR项目路演,近20个资本机构出席!诚邀您参加2020 Qualcomm XR生态合作伙伴大会
2020-08-20:GO语言中的协程与Python中的协程的区别?
Windows 10 蓝牙管理页面'添加蓝牙或其他设备'选项点击无响应的解决方案
List to map (split the list according to the key, and the value of the same key is a list)
The 4th China BIM (digital construction) manager Summit Forum will be held in Hangzhou in 2020
How to manage the authority of database account?
August 18, 2020: introduce Mr process?
Epu360: all the H5 templates you want are here, e-book, big turntable, red envelope rain, questionnaire survey
Python basic data type -- tuple analysis
Markdown tricks
Practice of Xiaoxiong school development board: real equipment access of smart street lamp sandbox experiment
Road to simple HTML + JS to achieve the most simple game Tetris
Reserved battery interface, built-in charge and discharge circuit and electricity meter, quickly help easily handle hand-held applications
迅为iMX6开发板-设备树内核-menuconfig的使用
轻量型 GPU 应用首选 京东智联云推出 NVIDIA vGPU 实例