【问题标题】:How to get an instance of a Vue Component from inside a component如何从组件内部获取 Vue 组件的实例
【发布时间】:2018-09-07 03:58:14
【问题描述】:

如何从我的SectionComponent.vue 文件中获取已导入组件的实例?

import ButtonComponent from './ButtonComponent.vue'; 

要获得它的一个实例,我想做这样的事情:

buttonComponent = Vue.component(ButtonComponent);

我的组件在我的组件数组中列出/定义为ButtonComponent 所以理论上我应该可以说:

let buttonComponent = Vue.component('button-component'); 

但这给了我不确定性。什么给了?

如果我全局注册它然后获取一个实例,它确实有效。

难道挂载的地方不适合测试这段代码吗?我的安装方法是在导入之前触发的吗?我只是在这里寻找一点清晰度,如果有人可以解释我将不胜感激!

【问题讨论】:

  • 你真的想在你的 SectionComponent 模板中渲染 ButtonComponent 吗?
  • 是的,我希望能够将按钮动态添加到部分组件。
  • 您可以通过标签在模板中使用ButtonComponent<button-component/>。您可以使用v-if 有条件地显示按钮,或使用v-for 显示按钮数组。
  • 基本上,您正在以一种非常非 Vue 的方式考虑这个问题。使用 Vue,您不必强制向 DOM 添加内容。相反,您根据数据的状态描述 DOM 在模板中的外观,而 Vue 会为您处理所有 DOM 操作。
  • @Bert 谢谢你,这确实有帮助。而不是向我的部分组件添加按钮。我已经有一个按钮,当发生一些动作时我会显示这个按钮。根据该动作发生的次数,我可以跟踪并显示多个按钮。这一切都是基于数据变化而不是添加新的组件实例而发生的。因为 Vue 已经为我做到了这一点?

标签: javascript vue.js ecmascript-6


【解决方案1】:

Vue 是一个声明式框架,这意味着您实际上并没有命令式地做事。相反,您将模板制定为状态的表示,然后 Vue 为您处理 DOM 操作。

这是一个基于您所描述的您想要做的示例。

console.clear()
Vue.component("button-component", {
  // identifier is just a property telling us which button this is so we 
  // can distinguish between them
  props:["identifier"],
  template: `<button @click="onClick">I'm button {{identifier}}</button>`,
  methods: {
    onClick() {alert(this.identifier)}
  }
})

new Vue({
  el: "#app",
  data:{
    howManyButtons: 0
  },
  methods: {
    onAddButton(){
      this.howManyButtons++
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="app">
  <button @click="onAddButton">Add a button component</button>
  <hr>
  <button-component v-for="btn in howManyButtons"
                    :identifier="btn"
                    :key="btn">
  </button-component>
</div>

在上面的示例中,我们希望根据“添加按钮”按钮被点击的次数来渲染按钮数量。为此,我们只需在单击按钮时增加一个计数器。然后在模板中,我们使用v-forrange variant 来渲染那么多按钮。

<button-component v-for="btn in howManyButtons"
                  :identifier="btn"
                  :key="btn">
</button-component>

希望这清楚地表明我们告诉 Vue 向 DOM 添加一个按钮是没有意义的。我们只是在模板中描述我们想要的按钮数量与计数器的数量一样多。

【讨论】:

    【解决方案2】:
    import ButtonComponent from './ButtonComponent.vue' 
    

    SectionComponent.vue 组件内部,

    export default {
      components: { ButtonComponent },
      // Whatever else you have in here
      data() { return {} },
      computed: {}
    }
    

    【讨论】:

    • 这就是我所拥有的。我的问题是如何获取 ButtonComponent 的实例并使用它?我想以编程方式向 SectionComponent 添加按钮。
    • 我不太确定你想问什么,但&lt;button-component&gt;&lt;/button-component&gt; 对你有用吗?
    • 确实如此。但我想用我的组件在 JS 中做相当于 createElement 的操作。例如,每当用户单击按钮时,我想获取按钮组件的实例并将其添加到 DOM 中。 developer.mozilla.org/en-US/docs/Web/API/Document/createElement
    • 您通常会在data 中创建一个数组,当用户单击按钮时附加到该数组,然后使用v-for 为每个数组元素生成一个按钮.
    猜你喜欢
    • 2019-01-19
    • 2018-10-01
    • 2017-01-03
    • 2018-01-03
    • 2020-01-25
    • 1970-01-01
    • 2018-09-08
    • 2019-05-12
    • 1970-01-01
    相关资源
    最近更新 更多