下面为大家分享一篇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"
一定要放在 你父组件调用子组件的 模块名上。
祝你们 编码愉快。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
如何解决父组件中vuex方法更新state子组件不能及时更新并渲染
以上就是VUEJS 2.0 子组件访问/调用父组件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号