乐闻世界logo
搜索文章和话题

How to use Vue.prototype or global variable in Vue 3?

1个答案

1

In Vue 3, the concept of Vue.prototype has been updated, corresponding to the configuration method for global properties and methods in Vue 2. For global properties and methods in Vue 3, it is recommended to use the new Composition API with the provide and inject mechanism. In Vue 3, the recommended approach is to use provide and inject with the Composition API to replace Vue.prototype from Vue 2. This method not only provides better type inference support but also integrates more effectively with Vue 3's reactivity system. Here is an example of how to use global variables in Vue 3:

Step 1: Create a Global Variable

First, you can create a JavaScript file to store your global variables or functions. For example, create a useGlobalProperties.js file:

javascript
import { reactive } from 'vue'; export const globalProperties = reactive({ appName: 'My Vue App', version: '1.0', increaseVersion() { this.version += 0.1; } });

Step 2: Provide Global Variables

In your root Vue component (typically App.vue or in main.js), use the provide method to provide these global variables:

javascript
import { createApp } from 'vue'; import App from './App.vue'; import { globalProperties } from './useGlobalProperties'; const app = createApp(App); app.provide('globalProps', globalProperties); app.mount('#app');

Step 3: Inject Global Variables into Components

Now you can access these global variables in any child component using the inject function:

vue
<template> <div> <h1>{{ globalProps.appName }}</h1> <button @click="globalProps.increaseVersion">Increase Version</button> <p>Current Version: {{ globalProps.version }}</p> </div> </template> <script> import { inject } from 'vue'; export default { setup() { const globalProps = inject('globalProps'); return { globalProps }; } }; </script>

This allows you to access and manipulate these global variables within components, and the approach is reactive, so the UI updates automatically.

Conclusion

Using Vue 3's provide and inject functionality can replace Vue.prototype from Vue 2, making the code more modular and maintainable. This approach aligns better with Vue 3's design philosophy and leverages Vue 3's reactivity system more effectively.

2024年8月9日 01:39 回复

你的答案