vue中子组件的created、mounted钩子中获取不到props中的值问题

121 阅读1分钟

父组件:

async fetchLatest() {
			console.log('请求最新课程列表');
			let res = await this.$req.get('/api/course/courses', {
				page: this.page,
				sort: 'latest'
			});
			this.latest = res.data;
			console.log(this.latest);
		},
        
// 在组件中
 <newLesson :items="latest"></newLesson>
        

子组件:

非常有趣的是

  • props传过来可以直接在HTML中使用 但是他不可以 直接在mouted created中this.xx 打印

要进行其他操作只能在watch中 拿到再处理、去执行其他的方法



<template>
	<view>
		<view class="w-686  zuixin ma0 a-center d-flex j-sb">
			<view class="left-ke">推荐课程</view>
			<view class="right-ke d-flex a-center ">
				查看更多

				<view class="d-flex a-center j-center" style="width: 40rpx;height: 40rpx; ">
					<image src="../../static/images/home/back.png" mode="" style="width: 36rpx;height: 36rpx;"></image>
				</view>
			</view>
		</view>

		<!-- 内容部分 -->
		<view class="container-new w-686 ma0 ">
			<view class="container-wrapper  j-sb d-flex" v-for="(item, index) in items" :key="index" :style="{ backgroundImage: 'url(' + item.cover + ')' }">
				<view class="left" v-show="item.is_vip"><image src="../../static/images/home/icon_is_vip.png" class="vip"></image></view>

				<view class="right">
					<view class="right-text">{{ item.title }}</view>
					<view class="rig-box d-flex a-center " style="height: 56rpx;">
						<view class="left" style="width: 80rpx;height: 40rpx;"><image src="../../static/images/home/tuwen.png" style="width: 100%;height: 100%;"></image></view>
						<view class="center">免费</view>
						<view class="right">{{ item.learn_number }}人在学</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default ({
	name: "newLession",
	props: {
		items: {
			type: Array,
			default: function() {
				return [];
			}
		},
	},
	data(){
		return {
			
			newData:[]
		}
	},
	mounted() {

		console.log('newLession 用的是async的方式发送网络请求:',this.items)//[] 这样是拿不到的
	},
	watch: {
	            //正确给 newData赋值的 方法
	            items: function(newVal,oldVal){
	                this.newData = newVal;  //newVal即是newLession
					console.log('newData:',this.newData)
	                // newVal&& this.drawChart(); //newVal存在的话执行drawChar函数
	            }
	        },
})
</script>