前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vue中props中值未监听

vue中props中值未监听

作者头像
阿超
发布2022-08-21 11:22:37
4320
发布2022-08-21 11:22:37
举报
文章被收录于专栏:快乐阿超快乐阿超

我今天简短测试了一下:

编写一个组件,给它设置一个props属性user

这里给它一个默认值{ age: 21 }

代码语言:javascript
复制
<template>
	<div>
		<slot :user="user">默认内容</slot>
	</div>
</template>

<script>
export default {
	props: {
		user: {
			type: Object,
			default: () => ({ age: 21 })
		}
	}
};
</script>

然后我们在外部引用该组件并传入该props

编写一个方法来改变当前userInfo的值

代码语言:javascript
复制
<template>
	<div>
		<navigation-link ref="navigationLink" :user="userInfo">
			<template #default="{user}">
				<div>user:{{ user }}</div>
				<div>user.name:{{ user.name }}</div>
			</template>
		</navigation-link>
		<button @click="click">userInfo:{{ userInfo }}</button>
	</div>
</template>
<script>
import NavigationLink from '@/components/navigation-link.vue';
export default {
	components: { NavigationLink },
	data() {
		return {
			userInfo: {
				gender: 'MALE'
			}
		};
	},
	methods: {
		click() {
			this.userInfo.name = 'ruben'
			this.$forceUpdate()
		}
	}
};
</script>

当前效果如下:

image-20220129130434431
image-20220129130434431

我们触发该事件,发现使用$forceUpdate使外部的userInfo成功更新

image-20220129130544722
image-20220129130544722

slot中的视图并未更新

我们换成$set

代码语言:javascript
复制
click() {
    this.$set(this.userInfo, 'name', 'ruben');
}

再来试试,发现成功绑定

image-20220129130635810
image-20220129130635810

此处如果我们没有传入名为userprop

我们也可以通过$refs直接直接绑定

代码语言:javascript
复制
click() {
    this.$set(this.$refs.navigationLink.user, 'name', 'ruben');
}

效果:

image-20220129130946646
image-20220129130946646
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-01-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档