Vue:父子组件之间的接口互调

一、父组件中调用子组件的方法

this.$refs.【子组件】.【子组件方法】

  1. 父组件部分
<template>
    <div id="parent">
        <ImportComponent ref="ImportComponent"></ImportComponent>
    </div>
</template>

<script>
	import ImportComponent from "@/components/common/ImportComponent";

	export default {
	    name: "Parent",
	    data() {
	        return { msg: "from parent" }
	    },
	    components: {ImportComponent},
	    methods: {
		    downloadTemplate{
	        	this.$refs.ImportComponent.downloadTemplateFile(this.msg); 
		    }
	    }
	}
</script>
  1. 子组件部分
<template>
    <div id="child">{{msg}}</div>
</template>

<script>
	export default {
	    name: "Child",
	    props: ["msg"],
	    data() {
	        return { msg: "" }
	    },
	    methods: {
	        downloadTemplateFile(msg) {
	            this.msg = msg
	        }
	    }
	}
</script>

二、子组件中调用父组件的方法

(1)this.$emit(【父组件方法】)

  1. 父组件部分
<template>
    <div id="parent">
        <ImportComponent ref="ImportComponent"></ImportComponent>
    </div>
</template>

<script>
	import ImportComponent from "@/components/common/ImportComponent";

	export default {
	    name: "Parent",
	    data () {
	        return { msg: "from parent" }
	    },
	    components: {
	        ImportComponent
	    },
	    methods: {
		    downloadTemplate{
	        	this.$refs.ImportComponent.downloadTemplateFile(this.msg); 
		    },
	        consoleMessage(msg){
	            console.log(msg)
	        }
	    }
	}
</script>
  1. 子组件部分
<template>
    <div id="child">{{msg}}</div>
</template>

<script>
	export default {
	    name: "Child",
	    props: ["msg"],
	    data () {
	        return { msg: "" }
	    },
	    methods: {
	        downloadTemplateFile(msg) {
	            this.msg = msg
	        },
	        childConsoleMessage(msg){
	            this.$emit("consoleMessage",msg);
	        }
	    }
	}
</script>

(2)provide + inject方式【可跨越多层传递数据】

  1. 父组件部分
<template>
    <div id="parent">
        <ImportComponent ref="ImportComponent"></ImportComponent>
    </div>
</template>

<script>
	import ImportComponent from "@/components/common/ImportComponent";

	export default {
	    name: "Parent",
	    data () {
	        return { msg: "from parent" }
	    },
	    provide(){
	        return {
	            parentMethod: this.consoleMessage
	        }
	    },
	    components: {
	        ImportComponent
	    },
	    methods: {
		    downloadTemplate{
	        	this.$refs.ImportComponent.downloadTemplateFile(this.msg); 
		    },
	        consoleMessage(msg){
	            console.log(msg)
	        }
	    }
	}
</script>
  1. 子组件部分
<template>
    <div id="child">{{msg}}</div>
</template>

<script>
	export default {
	    name: "Child",
	    props: ["msg"],
	    data () {
	        return { msg: "" }
	    },
	    inject: ["parentMethod"],
	    methods: {
	        downloadTemplateFile(msg) {
	            this.msg = msg
	        },
	        childConsoleMessage(msg){
	            this.parentMethod(msg);
	        }
	    }
	}
</script>

你可能感兴趣的:(前端开发)