【问题标题】:how to call child componenet on button click in parent componenet in vuejs如何在vuejs中的父组件中单击按钮时调用子组件
【发布时间】:2021-10-05 03:06:21
【问题描述】:

在父组件内部我包含子组件,我想在单击按钮时渲染(触发)子组件。这是我的代码

<script>
    import childComponenet'../../components/child-component.vue';

    export default {
        name:'parentComponenet',
        components:{
            childComponenet
        },
methods: {
            goToChild(tag){
              //go to child component
        }
</script>

【问题讨论】:

  • 显然在这里遗漏了很多代码。如果您只想在单击父级中的按钮时呈现子级,则在父模板中向子级添加“v-if”指令。使用父按钮切换将显示/隐藏孩子的布尔值。如果您想在子级中触发某些逻辑,您可以尝试将一个道具从父级传递给子级,当您单击按钮时由父级更新该道具。您还需要在孩子的道具上设置手表。当手表被触发时,运行逻辑在子组件中做你想做的事情。

标签: vue.js vuejs2 vue-component vuetify.js vue-router


【解决方案1】:

使用 $emit 或 vuex,但如果它是子级和父级,则使用 $emit

【讨论】:

    【解决方案2】:

    你到底是什么意思?单击父级上的按钮时显示子级?还是重新渲染?

    如果你想显示/渲染它,你可以这样做

    <template>
      <button @click="toggleShowChild">Show Child Component</button>
      <ChildComponent v-show="showChild"/>
    </template>
    
    <script>
        import childComponenet'../../components/child-component.vue';
    
        export default {
            name:'parentComponenet',
            components:{
                childComponenet
            },
            data () {
              return {
                showChild: false
              }
            },
            methods: {
                toggleShowChild() {
                  this.showChild = !this.showChild
                },
                goToChild(tag){
                  //go to child component
            }
      
    </script>
    

    这是更进一步的一步,您可以使用按钮切换子级。如果你想让按钮只显示孩子,你可以在按钮上做@click="showChild = true",根本不写方法。 你也可以用 v-if 代替 v-show 来做同样的事情。更多关于difference between v-if and v-show

    【讨论】:

    • 谢谢,这里的情况不同,我想点击按钮下载pdf。子组件实际上是一个通用的导出组件。每次我单击父级中的打印按钮时都需要下载 pdf。在我的情况下不需要显示/隐藏。我尝试了 ref.child.method(),但我想要更通用并在下载完成后销毁孩子。
    • @usercomapny 所以你想要的是在孩子身上调用一个方法?你的问题不是很清楚......如果你想在孩子身上调用一个方法,你可以这样做this.children[indexOfWantedChild].method()你的评论也不是最清楚的。
    猜你喜欢
    • 2023-03-13
    • 2017-07-15
    • 2022-10-04
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2021-07-19
    • 2018-11-06
    相关资源
    最近更新 更多