繁体   English   中英

我如何从子组件 vuejs 运行方法

[英]How i can run method from child component vuejs

我有父组件和 chidl 组件...当我单击父组件中的按钮时,我需要运行子方法。 示例代码:

家长

<template>
 <child-component></child-component>
 <button>Open Modal in child Component (set modal = true in child component)</button>
</template>

孩子:

<template>
<div v-if="modal">
 <button @click="modal = false">Close</button>
</div>
</template>
<script>
export default {
  data() {
    return {
     modal: false
    }
  } 
}
</script>

在 vue 中,您可以将函数作为道具传递。 因此,您可以向父组件中的备用模型添加一个函数,然后将其传递给您的子组件,以便它可以正常使用。 下面我举一个简单的例子。

小编辑,您可以使用绑定到模态状态的状态绑定一个类,如隐藏/显示类

// Html
<div id="app">
     <child v-bind:on-click="toggleModal" v-bind:status="modal" />
</div>


// Parent Component
var sample = new Vue({
     el: '#app',
     data: {
        modal: false
     },
     methods: {
        toggleModal() {
           this.modal = !this.modal
        }
     }
});

// Child component with function prop
Vue.component('child', {
     props: {
        onClick: Function,
        status: Boolean
     }
     template: '<button v-on:click="onClick()">Press Me</div>'
});

您可以通过不同的实现来实现这一点。 最常见的方法是通过emit (如果您使用的是 Redux 模式,另一种选择是通过分派动作)

首先,您要捕获父组件上的偶数并emit事件。 所以这应该是你的模板。

<template>
 <child-component></child-component>
 <button @click="click">Open Modal in child Component (set modal = true in child component)</button>
</template>

然后,您必须在click时调用的函数上emit一个事件(来自父组件)。 就像是:

click: function() {
  this.$emit('update');
}

最后,您的子组件需要“听到”该事件。 您可以在子组件的created函数上使用类似的方法来实现:

this.$parent.$on('update', this.updateModal);

this.updateModal是你的子组件上的一个函数,它只是翻转布尔值的值。

暂无
暂无

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

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