在 Vue.js 3 setup() 中访问 this.$root [英] Access this.$root in Vue.js 3 setup()

查看:551
本文介绍了在 Vue.js 3 setup() 中访问 this.$root的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Vue 2 中,您可以访问 created 钩子内的 this.$root.在 Vue 3 中,所有本来应该在 created 钩子中的东西现在都在 setup() 中.

In Vue 2, you can access this.$root inside the created hook. In Vue 3, everything that would have gone inside the created hook now goes in setup().

setup()中,我们无法访问this,那么,我们如何访问根实例上的任何内容?

In setup() we don't have access to this, so, how can we access anything on the root instance?

比如说,我在根实例上设置了一个属性:

Say, I set a property on the root instance:

const app = createApp(App).mount('#app');

app.$appName = 'Vue3';

我可以使用 this.$root.$appNamemounted() 访问 this,我如何在 中执行此操作setup()?

I can access this from mounted() with this.$root.$appName, how can I do this in setup()?

更新

如果我import它,我可以访问它:

I can access it if I import it:

import app from '@/main';
...
setup() {
    console.log(app.$appName) // Vue3

但是,如果我必须为每个文件都这样做,这很麻烦.

But, this is a hassle if I have to do this for every file.

更新 2

另一种解决方法是在 App.vue 中使用 provide(),然后在任何其他组件中使用 inject():

Another workaround is to use provide() inside App.vue and then inject() in any other components:

setup() {
    provide('$appName', 'Vue3')

setup() {
    inject('$appName') // Vue3

推荐答案

看来你需要 提供/注入.在你的 App.vue 中:

It seems you need provide / inject. In your App.vue:

import { provide } from 'vue';

export default {
  setup() {
    provide('appName', 'vue3')
  }
} 

提供它与您的app:

const app = createApp(App);
app.mount('#app');

app.provide('appName', 'Vue3');


然后在要访问此变量的任何子组件中,注入它:

import { inject } from 'vue'

export default {
  setup() {
    const appName = inject('appName');
  }
}

这篇关于在 Vue.js 3 setup() 中访问 this.$root的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆