有时候因为布局问题,需要子组件 把数据 传给父组件,并执行父级的某个方法,本文主要介绍了vuejs 2.0 子组件访问/调用父组件的方法(示例代码),需要的朋友可以参考下,希望能帮助到大家。
不多说上代码:
子组件:
<template>
<p class="isshowing" ref="isshowing">
<p class="menu-wrapper" ref="scroll_warpper" v-show="!hid_show_switch">
<ul ref="scroll_warpper_ul">
<li class="menu-item" @click="gotofatherdetail(233)">
</li>
</ul>
</p>
<v-loading class="isloading" v-show="hid_show_switch"></v-loading>
</p>
</template>
<script type="text/ecmascript-6">
export default {
methods: {
gotofatherdetail (itemid) {
// this.$parent.$router.push('gotodetail');
console.log('子组件方法走了' + itemid);
this.$emit('refreshbizlines', itemid); /* <span style="font-family: arial, helvetica, sans-serif;">itemid就是子要传的数据 - 这里很重要,refreshbizlines就是父组件$on监测的自定义函数不是父组件的自定义函数。*/</span>
}
}
};
</script>
父组件:
<template>
<p class="main-wrapper">
<p class="tab-wrapper">
<p class="tab-item">
<router-link to="/isshowing" class="table-item-text">正在热映</router-link>
</p>
<p class="tab-item">
<router-link to="/willshow" class="table-item-text">即将上映</router-link>
</p>
</p>
</p>
<router-view class="items-show" v-on:refreshbizlines="gotodetail" keep-alive></router-view>
</p>
</template>
<script type="text/ecmascript-6">
export default {
methods: {
gotodetail (itemid) {
console.log('父组件走你:' + itemid);
}
}<strong>
};
</script></strong>
父组件用 v-on 来做个监测的函数来检测,最终生成的代码是 类似
on: {
"refreshbizlines": function($event) {
_vm.gotodetail(123)
}
}
所以原理就是 子组件 访问 父组件的 检测函数 refreshbizlines ,访问了,则执行 refreshbizline 下面的 函数
gotodetail -- 也就是父组件的
gotodetail函数
注意 父组件 的
v-on:refreshbizlines="gotodetail"
一定要放在 你父组件调用子组件的 模块名上。
相关推荐:
vuejs2.0实现分页组件使用$emit进行事件监听数据传递的方法_javascript技巧
以上就是vuejs2.0子组件调用父组件的方法的详细内容。