繁体   English   中英

使用provide时如何引用Vue

[英]How to refer to Vue when using provide

我一直试图在不使用道具的情况下通过父组件将值传递给子组件。 我在父组件(不是最高父组件)上为此使用提供。 im 传递的值将动态更新,因此在阅读了 vue 文档后,我必须执行以下操作: Vue.computed(() => this.todos.length)但它会引发错误,因为 Vue 未定义。 我似乎无法像import Vue from 'vue' (或类似的东西)那样导入 Vue。 我怎样才能使这项工作? 老实说,即使我尝试传递一个 static 变量,我在(直接)子组件中仍然未定义,即使我使用与 vue 文档中完全相同的代码。
所以我有两个问题:

  1. 如何引用/导入 Vue 实例?
  2. 是否可以在直接父组件(不是根)上使用提供?

我正在使用 Vue3

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

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

您可以provide任何组件计算的值。 在父级中导入providecomputed ,并像这样使用它们:

家长

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

在孩子中导入inject

孩子

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM