父组件调用子组件方法
关键字:$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>
子组件使用父组件属性
在父组件中导入子组件,并添加 自定义名称,如下::searchData为自定义名称,searchData为父组件的data中的属性searchData:{}
<net-work :searchData="searchData"/>
子组件添加props,例如下,searchData为第一步的自定义名称,type为父组件searchData:{}的类型,default为默认值,可以省略
props: {searchData: {type: Object,default: {}}},
子组件使用,如下:
let serverName = this.searchData.servername;let startTime = this.searchData.startTime;let endTime = this.searchData.endTime;
