当我们使用vue脚手架创建项目时,关于父子组件通过路由的方式声明关系,如下:
const routes = [
{ path: '/', redirect: '/home' },
{
path: '/home',
component: Home,
redirect: '/query',
children: [
{ path: '/query', component: Days, name: 'days' },
{ path: '/monthsQuery', component: Months },
{ path: '/yearTotal', component: Years }
]
}
]
那父子组件的通信怎么实现???
百度了很多的文章,都没有讲到这方面,都是父组件导入子组件,如果使用了路由的方式声明了关系,再导入子组件就会发生组件重复。
那如何解决呢?
<router-view :rawData="rawData" @whichMonitor="currentMonitor" ref="monitorChild"/>
看上面的这段代码
router-view这是路由占位符,也就是写在父组件中的
<el-main>
<!-- 路由占位符 -->
<router-view
:rowdata='datas'
ref="days"
></router-view>
</el-main>
子组件:
export default {
// 接收父组件传递过来的数据
props: [
// $attrs.date
'rowdata'
],
data(){}.........
主要是子组件访问父组件的属性
父组件:
startTime: today,
endTime: endday,
dimPid: ''
子组件:
startTime: this.rowdata.startTime,
endTime: this.rowdata.endTime,
dimPid: this.rowdata.dimPid
父组件访问子组件的方法
也就是第二个参数
父组件:
data:
// activePath
activePath: this.$route.path,
methods:
this.activePath = this.$route.path
if (this.activePath === '/query') {
await this.$refs.days.queryData()
}
if (this.activePath === '/monthsQuery') {
console.log(typeof this.$refs.days)
await this.$refs.days.queryMonthList()
}
if (this.activePath === '/yearTotal') {
await this.$refs.days.queryYearList()
}
以上就是:
希望能帮助需要的人!!!