vue2.0 父子组件间方法互调
2018-11-12 本文已影响24人
博客已迁移I米阳
父组件调用子组件方法
关键字:$refs 是一个对象,持有注册过的 ref 特性的所有DOM元素和组件实例
子组件,如下代码不用做任何特殊处理:
child.vue
<template>
<div>
<h1>I am child</h1>
</div>
</template>
<script>
export default {
name: "child",
methods: {
child: function () {
alert("I am child");
}
}
}
</script>
父组件:
parents.vue
<template>
<div>
<el-button @click="demo01">调用子组件方法</el-button>
<child-com ref="getChild"></child-com>
</div>
</template>
<script>
import childCom from './child'
export default {
components: {childCom},
name: "parents",
methods: {
demo01: function () {
this.$refs.getChild.child();
}
}
}
</script>
父组件中,我们通过import 导入子组件后,如果想用子组件提供的方法,我们需要再子组件中 加入 ref='xxx' xxx仅仅是个占位符名称随意。 然后编写方法调用子组件方法。 直接通过this.$refs.占位符.子组件方法名()
调用。
子组件调用父组件方法
关键字:$emit 触发当前实例上的事件。附加参数都会传给监听器回调。
我们先看父组件。编写了自己的parents() 方法外,引用了子组件。 为了能让 parents()方法能被child子组件待用,需要在Dom节点上添加 @xxx="parents()"。 其中xxx为子组件调用时使用的名称。 parents()就是父组件的方法。
parents.vue
<template>
<div>
<child-com @par="parents"></child-com>
</div>
</template>
<script>
import childCom from './child'
export default {
components: {childCom},
name: "parents",
methods: {
parents: function (parameter) {
alert(`I am ${parameter}`);
}
}
}
</script>
<style scoped>
</style>
子组件代码如下,需要添加调用父组件方法,并在该方法下通过this.$emit('xxx', 'parameter')调用父组件方法。 其中xxx为父组件给子组件提供的占位符,parameter为父组件方法的参数。
child.vue
<template>
<div>
<el-button @click="childM">调用父组件方法</el-button>
<h1>I am child</h1>
</div>
</template>
<script>
export default {
name: "child",
methods: {
childM:function () {
this.$emit('par', 'meyoung')
}
}
}
</script>