子组件调用父组件的方法,并传值给父组件:依靠 事件绑定机制 传递
index.html
<div id="app"> <p>这是index.html</p> <my-c></my-c> </div>
index.js
// 导入vue import Vue from 'vue/dist/vue.js' // 导入自定义组件模板 import C from './C.vue' // 定义为全局子组件 Vue.component('my-c',C) const vm = new Vue({ el: '#app', data: { }, })
C.vue
<template> <div class="one"> <h1>这是C.vue文件内容</h1> <h1>这是D.vue文件的值----{{dataFromSon}}</h1> <!-- 事件绑定传值 --> <my-d @father01="show01" @father02="show02"></my-d> </div> </template> <script> // 导入子组件 import D from './D.vue' export default { // 定义为私有子组件 components: { 'my-d': D }, data() { return { dataFromSon: '' } }, methods: { show01(arg1,arg2) { console.log("这是父组件的方法!!" + arg1 + arg2); }, show02(arg) { this.dataFromSon = arg } } } </script> <style lang="less" scoped> .one { border: 1px solid red; h1 { color: red; } } </style>
D.vue
<template> <div> <h3>这是D.vue文件内容</h3> <h4 @click="sonHander01">调用到父组件father01方法</h4> <h4 @click="sonHander02">调用到父组件father02方法</h4> </div> </template> <script> export default { data() { return { sondata: '儿子的值' } }, methods: { sonHander01() { this.$emit('father01','参数1','参数2') }, sonHander02() { this.$emit('father02',this.sondata) } } } </script> <style lang="less" scoped> div { border: 2px dashed purple; margin: 20px; h3 { color: green; } } </style>