最近有一个需求,在页面上调用组件,在点击子组件时调用父组件内定义的方法。如果大家有更多更好的方法,欢迎指正。
1.创建一个组件,并在页面上调用引用
2.在页面引用组件时,通过v-on绑定父组件内定义好的方法
3.在子组件内绑定@tap触发子组件内定义的方法,同时在组件内通过this.$emit触发父组件内绑定的方法
4.示例代码
// 父页面
<template>
<view class="father">
<child v-on:ToChange="change"></child>
</view>
</template>
<script>
import child from '../../components/child'
export default {
...
methods: {
change(){
console.log("触发了父页面内的方法");
},
},
components:{
child
}
}
</script>
// 子组件
<template>
<view @tap="change()">
子组件
</view>
</template>
<script>
export default {
...
methods:{
change(){
this.$emit("Tochange");
console.log("触发了子组件内的方法");
}
}
}
</script>