方式一
$parent
父组件
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from './child';
export default {
components: {
child
},
methods: {
fatherMethod(str) {
console.log(str);
}
}
};
</script>
子组件
<template>
<div>
<button @click="childMethod">点击</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$parent.fatherMethod('hello');
}
}
};
</script>
方式二
props
父组件
<template>
<div>
<child :fatherMethod="fatherMethodOther"></child>
</div>
</template>
<script>
import child from './child';
export default {
components: {
child
},
methods: {
fatherMethodOther(str) {
console.log(str);
}
}
};
</script>
子组件
<template>
<div>
<button @click="childMethod">点击</button>
</div>
</template>
<script>
export default {
props: {
fatherMethod: {
type: Function,
default: null
}
},
methods: {
childMethod() {
if (this.fatherMethod) {
this.fatherMethod('hello');
}
}
}
};
</script>
方式三
$emit
父组件
<template>
<div>
<child @fatherMethod="fatherMethodOther"></child>
</div>
</template>
<script>
import child from './child';
export default {
components: {
child
},
methods: {
fatherMethodOther(str) {
console.log(str);
}
}
};
</script>
子组件
<template>
<div>
<button @click="childMethod">点击</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$emit('fatherMethod', 'hello');
}
}
};
</script>
第一种不推荐,一般第三种。