使用provide时如何引用Vue

How to refer to Vue when using provide

我一直在尝试在不使用 props 的情况下通过父组件将值传递给子组件。我在父组件(不是最高父组件)上使用 provide for this。我传递下来的值将动态更新,所以在阅读 vue 文档后我必须做类似的事情: Vue.computed(() => this.todos.length) 但它会抛出一个错误,因为 Vue 是未定义的。我似乎无法像这样 import Vue from 'vue' (或类似的东西)导入 Vue。我怎样才能使这项工作?老实说,即使我尝试传递一个静态变量,我在(直接)子组件中也会得到 undefined,即使我使用与 vue 文档中完全相同的代码也是如此。
所以我有两个问题:

  1. 如何refer/import Vue实例?
  2. 是否可以在直接父组件(不是根组件)上使用 provide?

我正在使用 Vue3

您可以使用 getCurrentInstance 获取实例,但您不需要这样做:

import { getCurrentInstance } from 'vue';
setup() {
   const internalInstance = getCurrentInstance();
}

您可以 provide 从 任何组件计算 。在 parent 中导入 providecomputed 并像这样使用它们:

Parent

import { provide, computed } from 'vue';
setup() {
   ...
   const total = computed(() => x.value + y.value);  // Some computed
   provide('total', total);
}

在 child 中导入 inject:

Child

import { inject } from 'vue';
setup() {
   ...
   const total = inject('total');
}

这是一个演示(导入语法略有不同,因为 CDN 不使用实际导入):

const { createApp, ref, computed, provide, inject } = Vue;

const app = createApp({});

// PARENT
app.component('parent', {
  template: `
  <div class="parent">
    <child></child>
    <button @click="x++">Increment</button> (from Parent)
  </div>
  `,
  setup() {
    const x = ref(5);
    const y = ref(10);
    const total = computed(() => x.value + y.value);
    provide('total', total);
    
    return {
        x
    }
  }
});

// CHILD
app.component('child', {
  template: `
  <div class="child">
    Total: {{ total }}
  </div>
  `,
  setup() {
    const total = inject('total');
    
    return {
        total
    }
  }
});

app.mount("#app");
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}
.parent, .child { padding: 24px; }
.parent {
  background: #dddddd;
}
.child {
  margin: 6px 0;
  background: #ddeeff;
}
<div id="app">
  <parent></parent>
</div>

<script src="https://unpkg.com/vue@next"></script>