Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the new features of Vue.js 3.0

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains what are the new features of Vue.js 3.0. the content of the explanation is simple and clear, and it is easy to learn and understand. please follow the editor's train of thought to study and learn what the new features of Vue.js 3.0are.

1. Initialize the project

/ / ① npm I-g @ vue/cli / / ② vue create my-project / / ③ npm install @ vue/composition-api-S / / ④ main,js import Vue from 'vue' import VueCompositionApi from' @ vue/composition-api' Vue.use (VueCompositionApi)

2. Setup method

Setup is a new method of manipulating component properties in vue3.x. It is a unified API that exposes all the properties and methods within the component.

2.1 timing of execution

The timing of setup execution is after beforeCreate and before created.

Setup (props, ctx) {console.log ('setup')}, beforeCreate () {console.log (' beforeCreate')}, created () {console.log ('created')}

2.2 accept props data

/ / receive props data through the first parameter of the setup function: setup (props) {console.log (props)}, / / define the parameter name allowed to be passed by the current component in props: props: {p1: String} / * {} p1: "pass value to com-setup" get p1: "reactiveGetter () set p1: reactiveSetter (newVal) _ proto__: Object * /

2.3 context

The second formal parameter of the setup function is a context object, which contains some useful properties that need to be accessed through this in vue 2.x. In vue 3.x, they are accessed as follows:

Setup (props, ctx) {console.log (ctx) console.log (this) / / undefined}, / * attrs: Object emit: initiate () listeners: Object parent: VueComponent refs: Object root: Vue. * /

Note: this cannot be accessed in the setup () function

3. Reactive

The reactive function takes a normal function and returns a responsive data object.

The reactive function is equivalent to the Vue.observable () function in vue 2.x, and the reactive () function is provided in vue 3.x to create responsive data objects. The basic code example is as follows:

The current count value is: {{count}}

+ 1 import {reactive} from'@ vue/composition-api' export default {setup (props, ctx) {/ / create a responsive data object, and the resulting state is similar to the responsive object const state = reactive ({count: 0}) state.count + = 1 console.log (state) / / setup returned by data () in vue 2.x. For template to use return state}}

4. Ref

The ref () function is used to create a responsive data object based on a given value, and the return value of the ref () function call is an object that contains only one .value attribute:

02.ref.vue file

RefCount: {{refCount}}

+ 1 import {ref} from'@ vue/composition-api' export default {setup () {/ create a responsive data object count with an initial value of 0 const refrefCount = ref (0) / / if you want to access the value of the responsive data object created by ref (), you must pass the .value attribute. The .value attribute console.log (refCount.value) / / output 0 / / Let the value of refCount + 1 refCount.value++ / / print the value of refCount again console.log (refCount.value) / / output 1 return {refCount}} only inside the setup

4.1 access to responsive data created by ref in a reactive object

When the responsive data object created by ref () is mounted on reactive (), the responsive data object is automatically expanded to the original value and can be accessed directly without going through .value, for example:

Setup () {const refrefCount = ref (0) const state = reactive ({refCount}) console.log (state.refCount) / / output 0 state.refCount++ / / No .value is needed to directly access the original value console.log (refCount) / / output 1 return {refCount}}

Note: the new ref will overwrite the old ref. The sample code is as follows:

Setup () {/ / create ref and mount it to reactive const C1 = ref (0); const state = reactive ({C1}); / / create ref again, named c2 const c2 = ref (9); / / replace old ref C1 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}

5. IsRef

IsRef () is used to determine whether a value is an object created by ref (); application scenarios: when you need to expand a value that may be created for ref (), for example:

Import {ref, reactive, isRef} from "@ vue/composition-api"; export default {setup () {const unwrapped = isRef (foo)? Foo.value: foo}}

6. ToRefs

The toRefs () function can convert a responsive object created by reactive () into a normal object, but each attribute node on this object is responsive data of type ref ().

03.toRefs.vue file

{{count}}-{{name}}

+ 1 + 1 import {reactive, toRefs} from "@ vue/composition-api"; export default {setup () {/ / responsive data const state = reactive ({count: 0, name: "zs"}); / / method const add = () = > {state.count + = 1;} Return {/ / non-responsive data / /... state, / / responsive data... toRefs (state), add};}}

7. Computed calculation properties

7.1 read-only calculation properties

04.computed.vue file

RefCount: {{refCount}}

Calculate the value of the attribute computedCount: {{computedCount}}

The value of refCount + 1 calculation attribute computedCount + 1 import {computed, ref} from'@ vue/composition-api' export default {setup () {const refrefCount = ref (1) / / read-only let computedcomputedCount = computed (() = > refCount.value + 1) console.log (computedCount) return {refCount, computedCount}

7.2 Readable and writeable calculation properties

04.computed.vue file

RefCount: {{refCount}}

Calculate the value of the attribute computedCount: {{computedCount}}

RefCount + 1 import {computed, ref} from'@ vue/composition-api' export default {setup () {const refrefCount = ref (1) / / readable and writable let computedcomputedCount = computed ({/ / value function get: () = > refCount.value + 1 / / assignment function set: val = > {refCountrefCount.value = refCount.value-5}}) console.log (computedCount.value) / / the operation of assigning values to calculated attributes After the set function computedCount.value = 10 console.log (computedCount.value) / / triggers the set function, the value of count will be updated console.log (refCount.value) return {refCount, computedCount}

8. Watch

The watch () function is used to monitor changes in certain data items, thus triggering certain actions, which need to be imported on demand before use:

Import {watch} from'@ vue/composition-api'

8.1 basic usage

05.watch.vue file

RefCount: {{refCount}}

Import {watch, ref} from'@ vue/composition-api' export default {setup () {const refrefCount = ref / / defines watch, as long as the count value changes The watch callback / / component will be triggered to execute watch watch (() = > console.log (refCount.value), {lazy: false}) setInterval (() = > {refCount.value + = 2}, 5000) return {refCount}} when it is first created.

8.2 Monitoring data sources

Monitor data sources of type reactive:

05.watch.vue file

Count: {{count}}

/ / not responsive data import {watch, ref, reactive} from'@ vue/composition-api' export default {setup () {const state = reactive ({count: 100}) watch (/ / listening count () = > state.count, / / if the transformation executes the following functions (newVal, oldVala) = > {console.log (newVal, oldVala)} {lazy: true}) setInterval (() = > {state.count + = 2}, 5000) return state}}

Monitor data sources of type ref:

Export default {setup () {/ / define data source let count = ref (0) / / specify the data source watch (count, (count, prevCount) = > {console.log (count, prevCount)}) setInterval (() = > {count.value + = 2}, 2000) console.log (count.value) return {count}

8.3 listening on multiple data sources

Monitor data sources of type reactive:

Export default {setup () {const state = reactive ({count: 100, name: 'houfei'}) watch (/ / listen count name [() = > state.count, () = > state.name], / / if the transformation executes the following functions ([newCount, newName], [oldCount, oldName]) = > {console.log (newCount, oldCount) console.log (newName) OldName)}, {lazy: true} / / when watch is created Do not execute the code in the callback function) setTimeout (() = > {state.count + = 2 state.name = 'qweqweewq'}, 3000) return state}}

Monitor data sources of type ref:

Export default {setup () {/ / define the data source const count = ref (10) const name = ref ('zs') / / specify the data source watch ([count, name], ([newCount, newName], [oldCount, oldName]) > {console.log (newCount, oldCount) console.log (newName, oldName)} {lazy: true}) setInterval (() = > {count.value + = 2}, 2000) console.log (count.value) return {count}}

8.4 clear Monitoring

The watch monitor created within the setup () function automatically stops when the current component is destroyed. If you want to explicitly stop a monitor, you can call the return value of the watch () function, with the following syntax:

/ / create a monitor and get the stop function const stop = watch (() = > {/ *... * /}) / / call the stop function to clear the corresponding monitoring stop ()

Count: {{count}}

Stop listening to import {watch, ref, reactive} from "@ vue/composition-api" Export default {setup () {/ / define data source const count = ref (10) const name = ref ('zs') / / specify the data source to monitor const stop = watch ([count, name], ([newCount, newName], [oldCount, oldName]) = > {console.log (newCount, oldCount) console.log (newName, oldName)} {lazy: true}) setInterval (() = > {count.value + = 2 name.value = 'houyue'}, 2000) / / stop monitoring const stopWatch = () = > {console.log ("stop monitoring But the data is still changing ") stop ()} console.log (count.value) return {stop, count, stopWatch}

8.5 clear invalid asynchronous tasks in watch

Sometimes, when the value monitored by watch changes, or after the watch itself is stop, we expect to be able to clear those invalid asynchronous tasks, and a cleanup registrator function is provided in the watch callback function to perform the cleanup. The cleanup function is called under the following circumstances:

Watch has been repeated.

Watch was forced to stop.

An example of code in Template is as follows:

Keywords:--- {{keywords}}

An example of code in Script is as follows:

Import {watch, ref, reactive} from "@ vue/composition-api"; export default {setup () {/ / define responsive data keywords const keywords = ref (""); / / Asynchronous tasks: print the keywords entered by the user const asyncPrint = val = > {/ / print return setTimeout after a delay of 1 second (() = > {console.log (val);}, 1000) }; / / define watch snooping watch (keywords, (keywords, prevKeywords, onCleanup) = > {/ / execute asynchronous task, and get timerId const timerId = asyncPrint (keywords) that closes asynchronous task; / / if watch snooping is executed repeatedly, the last outstanding asynchronous task onCleanup (() = > clearTimeout (timerId)) will be cleared first. }, / / watch is not executed {lazy: true} when it is first created; / / return the data needed in template to return {keywords};}}

9. Value passed by provide & inject component

Provide () and inject () enable data transfer between nested components. These two functions can only be used in the setup () function. The provide () function is used in the parent component to pass data down; in the child component, inject () is used to get the data passed by the upper layer.

9.1 sharing common data

App.vue root component:

Parent import {ref, provide} from'@ vue/composition-api' import Son from'. / components/06.son.vue' export default {name: 'app', components: {' son': Son}, setup () {const color = ref ('green') provide (' themecolor') Color) return {color}

06.son.vue son components:

Son component import {inject} from'@ vue/composition-api' import Grandson from'. / 07.grandson.vue' export default {components: {'grandson': Grandson}, setup () {const color = inject (' themecolor') return {color}

07.grandson.vue son components:

Grandson component import {inject} from'@ vue/composition-api' export default {setup () {const color = inject ('themecolor') return {color}

9.2 sharing ref responsive data

App.vue root component:

Parent component import {provide} from'@ vue/composition-api' import Son from'. / components/06.son.vue' export default {name: 'app', components: {' son': Son}, setup () {provide ('themecolor',' red')}}

06.son.vue son components:

Son component import {inject} from'@ vue/composition-api' import Grandson from'. / 07.grandson.vue' export default {components: {'grandson': Grandson}, setup () {const color = inject (' themecolor') return {color}

07.grandson.vue son components:

Template > grandson component import {inject} from'@ vue/composition-api' export default {setup () {const color = inject ('themecolor') return {color}

10. Reference template ref of the node

10.1 reference to dom

TemplateRefOne import {ref, onMounted} from'@ vue/composition-api' export default {setup () {/ / create a DOM reference const h4Ref = ref (null) / / after DOM is loaded for the first time To get the reference to the element onMounted (() = > {/ / set the font color for the dom element / / h4Ref.value is the native DOM object h4Ref.value.style.color = 'red'}) / / return the created reference to return {h4Ref}}

10.2 references to components

App parent component:

The parent component shows the value of the child component import Son from'. / components/06.son.vue' export default {name: 'app', components: {' son': Son} Setup () {const comRef = ref (null) const showComRef = () = > {console.log (comRef) console.log ('str1 is' + comRef.value.str1) comRef.value.setStr1 ()} return {comRef, showComRef}

06.son.vue sub-component:

Son component

{{str1}}

Import {ref} from'@ vue/composition-api' export default {setup () {const str1 = ref ('this is a subcomponent!') Const setStr1 = () = > {str1.value = 'assigned'} return {str1, setStr1}

11 nextTick

09.nextTick component

Learn $nextTick

Show the text box export default {data () {return {isShowInput: false}}, methods: {showInput () {this.isShowInput =! this.isShowInput / / console.log (this.$refs) this.$nextTick (() = > {this.$refs.ipt.focus ()})} Thank you for reading The above is the content of "what are the new features of Vue.js 3.0". After the study of this article, I believe you have a deeper understanding of the new features of Vue.js 3.0. the specific usage still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report