我今天简短测试了一下:
编写一个组件,给它设置一个props
属性user
这里给它一个默认值{ age: 21 }
<template>
<div>
<slot :user="user">默认内容</slot>
</div>
</template>
<script>
export default {
props: {
user: {
type: Object,
default: () => ({ age: 21 })
}
}
};
</script>
然后我们在外部引用该组件并传入该props
编写一个方法来改变当前userInfo
的值
<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>
当前效果如下:
我们触发该事件,发现使用$forceUpdate
使外部的userInfo
成功更新
但slot
中的视图并未更新
我们换成$set
click() {
this.$set(this.userInfo, 'name', 'ruben');
}
再来试试,发现成功绑定
此处如果我们没有传入名为user
的prop
我们也可以通过$refs
直接直接绑定
click() {
this.$set(this.$refs.navigationLink.user, 'name', 'ruben');
}
效果:
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有