第一种方法是在子组件里用 e m i t 向 父 组 件 触 发 一 个 事 件 , 父 组 件 监 听 这 个 事 件 就 行 了 。 具 体 就 是 子 组 件 触 发 emit向父组件触发一个事件,父组件监听这个事件就行了。 具体就是子组件触发 emit向父组件触发一个事件,父组件监听这个事件就行了。具体就是子组件触发emit绑定的事件:fatherMethod, 然后父组件监听fatherMethod, - 旦fatherMethod被触发,便会触发父组件的fatherMethod方法。
父组件
<template>
<div>
<child @fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from '~/components/test/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('父组件的方法');
}
}
};
</script>
子组件
<template>
<div>
<button @click="childMethod()">点击</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$emit('fatherMethod');
}
}
};
</script>
第二种是父组件把方法传入子组件中,在子组件里直接调用这个方法。
具体:在子组件props中定义属性fatherMethod,类型为function ,然后在父组件中把要触发的方法名传递给fatherMethod属性,最后在子组件中判断fatherMethod是否存在,是的话直接执行这个方法。
父组件
<template>
<div>
<child :fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from '~/components/test/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('父组件的方法');
}
}
};
</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();
}
}
}
};
</script>
如果是在.html文件中引入vue.js的话是这样的,需要注意命名的写法
第一种方法
<body>
<div id="app">
<blog-post @father-method="fatherMethod"></blog-post>
</div>
</body>
</html>
<script>
Vue.component('blog-post', {
template: `<button @click="childMethod">
点击子组件按钮调用父组件方法</button>`,
methods: {
childMethod: function() {
this.$emit('fatherMethod');
}
}
})
const vm = new Vue({
el: '#app',
methods: {
fatherMethod: function() {
console.log('父组件方法')
}
}
})
//在DOM模板中使用时不能使用v-on来监听camelCase事件
//fatherMethod改成father - method
</script>
第二种方法
<body>
<div id="app">
<button-son :father-method="fatherMethod">
</button-son>
</div>
<script type="text/javascript">
Vue.component('button-son', {
props: {
fatherMethod: {
type: Function,
default: null
}
},
template: `<div><button @click="childMethod">子组件按钮</button></div>`,
methods: {
childMethod: function() {
if (this.fatherMethod) {
this.fatherMethod();
}
}
}
})
var vm = new Vue({
el: "#app",
methods: {
fatherMethod: function() {
console.log('父组件的方法');
}
}
})
//我犯的错误
//1.<button-son :father-method="fatherMethod"> :写成了@
//prop中可以传入对象,虽然当前对象放的是一个方法名,也不能用@,因为prop是通过v-bind动态赋值的
//2.father-method写成了fatherMethod
// HTML 中的 attribute 名是大小写不敏感的,所以浏览器会把所有大写字
// 符解释为小写字符。这意味着当你使用 DOM 中的模板时,
// camelCase (驼峰命名法) 的 prop 名需要使用其等价的
// kebab-case (短横线分隔命名) 命名
//3.<button @click="childMethod">
//写成了childMethod()
</script>