我今天简短测试了一下:
编写一个组件,给它设置一个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');
}效果:



