【问题标题】:Dynamically switch components and call the function save of active component动态切换组件并调用活动组件的函数save
【发布时间】:2020-09-06 20:25:00
【问题描述】:

为了从一个组件切换到另一个组件,我使用 vue 中的 <component> 元素,它用于通过添加 :is 特殊属性来动态呈现组件。 <component :is="selected"></component>
我的代码:

<template>
  <div>
    <component :is="selected"></component>
    <b-button @click="nextComponent">next</b-button>
  </div>
</template>

在我们的组件文件夹中有两个名为 Home 和 Contact 的新组件。

<script>
import Home from "./components/Home";
import Contact from "./components/Contact";

export default {
  data: function() {
    return {
      tabs: ["Home", "Contact"],
      selected: "Home"
    };
  },
  components: {
    Home,
    Contact
  },
  nextComponent () {
     let index = 0
     let nameComponent = this.tabs[index]
     const total = this.tabs.length
     if (index >= total) {
       index = 0
       this.selected = nameComponent
       } else {
        index++
        this.selected = nameComponent
       }
     this.$emit('save')
  }
};
</script>

问题是如何调用活动组件的函数save。我的意思是如果 selected = Home 在 Home.Vue 中如何调用 save

我的组件里有这些功能

mounted () {
    this.$on('save', this.save)
},
methods: {
save () {
   console.log('to check if it works')
 }
}

但它不起作用

【问题讨论】:

    标签: javascript html vue.js vue-component


    【解决方案1】:

    执行此操作时,您只是注册了要在 'save' 事件上触发的 save 函数。你没有执行/调用mounted钩子中的函数。

    mounted () {
        this.$on('save', this.save)
    },
    

    要在初始挂载时调用它,只需执行mounted 中的函数即可。

    像这样:

    mounted () {
        this.$on('save', this.save);
        this.save() // <-- calling the function when component mounts
    
    },
    

    现在这个函数 save 将在初始挂载时调用,并且只要它收到 'save' 事件。

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 2012-10-18
      相关资源
      最近更新 更多