今天自己在仿写网易云音乐的项目时,遇到一个问题,在使用一个播放的组件的时候,需要把父组件的url 传递到子组件使用,但是子组件获取到的url一直是undefined.
问题分析:
1.数据获取是异步请求
2.父子组件传值也是异步的
直观一点直接看代码:
template:
//父组件
<div class="video">
//子组件先与数据回来执行,所以拿到的url是undefined
//<Playcard ref="video" :url="Urldata.url" />
//解决方式
<Playcard v-if="Urldata.url" ref="video" :url="Urldata.url" />
</div>
js:
data () {
return {
simidata:[],
detaildata:{},
brs:{},
Urldata:{}
}
},
created () {
this.init();
},
methods: {
async init(){
let mvid = this.$route.params.id
//获取相似的mv
let {data} = await this.$request.Getsimimv({mvid})
//获取mv 的详情
let backdata = await this.$request.Getmvdetail({mvid});
//获取mv的url
let urldata = await this.$request.Getmvurl({id:mvid})
this.simidata = data.mvs
this.detaildata = backdata.data.data
this.brs = backdata.data.data.brs
this.Urldata = urldata.data.data
console.log(this.Urldata.url); //url
}
}
子组件
<template>
<div ref="player" class="play"></div>
</template>
<script>
import Player from "xgplayer";
export default {
props: ["url"],
mounted() {
this.initplay()
},
created () {
console.log(this.url); //undefined
},
methods() {
initplay(){
......
}
},
};
</script>