Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue 3 app.runWithContext() Function

Vue 3 app.runWithContext() Function Explained


Vue3 Global API Vue 3 Global API

app.runWithContext() function is a powerful tool that allows us to execute code within a specific application context, which is very useful for managing state or processing logic outside Vue components.

If you have more questions about app.runWithContext() or need further help, feel free to ask!


1. What is app.runWithContext()?

app.runWithContext() is an API provided by Vue 3 that allows you to execute a piece of code within the current application's context. This means that code executed in runWithContext() can access the application's context information, such as provide/inject, global state, etc.

1.1 Basic Syntax

Example

app.

runWithContext

(

(

)

=>

{

 

// code executed here runs within the current application's context

}

)

;

1.2 Use Cases


2. How to Use app.runWithContext()?

2.1 Basic Usage

Suppose you have a Vue application and you want to access the application's context in a utility function; you can use app.runWithContext():

Example

import

{

createApp

}

from

'vue'

;

const

app

=

createApp

(

{

}

)

;

app.

provide

(

'globalData'

,

'Hello, Vue 3!'

)

;

app.

runWithContext

(

(

)

=>

{

 

const

globalData

=

app._context.

provides

.

globalData

;

  console.

log

(

globalData

)

;

// output: Hello, Vue 3!

}

)

;

In this example, we provided a value globalDatain the application context, then accessed this value in runWithContext() .

2.2 Using in Asynchronous Operations

When handling asynchronous operations, ensure Vue's context information is accessible in the callback function:

Example

app.

runWithContext

(

async

(

)

=>

{

 

const

response

=

await fetch

(

'https://api.example.com/data'

)

;

 

const

data

=

await response.

json

(

)

;

 

 

// Vue's context information can be accessed here

 

const

globalData

=

app._context.

provides

.

globalData

;

  console.

log

(

globalData

)

;

}

)

;

2.3 Combining with provide/inject

app.runWithContext() is very suitable for combining with provide/inject to ensure injected values are accessible anywhere:

Example

app.

provide

(

'user'

,

{

name

:

'Alice'

,

age

:

25

}

)

;

app.

runWithContext

(

(

)

=>

{

 

const

user

=

app._context.

provides

.

user

;

  console.

log

(

user

)

;

// output: { name: 'Alice', age: 25 }

}

)

;


3. Notes


Vue3 Global API Vue 3 Global API