Vue.js 2:如何将父组件过滤后的数组替换原props传给子组件
Vue.js 2 处理屏蔽用户帖子的正确方式
首先明确:Vue 的 props 是单向数据流,父组件不能直接修改自身的 props。如果你的posts是从上层组件传递来的 props,得通知上层组件更新;如果posts是父组件自己的本地数据(可能你误标成了props),直接替换数组即可,不需要用this.$set。
情况1:父组件的posts是本地data(最常见场景)
如果posts是父组件自己维护的本地数据,直接把过滤后的postData赋值给this.posts就行,Vue 会自动监听数组替换的变化:
// 父组件代码 export default { data() { return { posts: [] // 本地维护的帖子数组 } }, methods: { removeBlockedUserPosts(blockedUserName) { // 过滤掉被屏蔽用户的帖子 const postData = this.posts.filter(post => post.userName !== blockedUserName); // 直接替换数组,响应式自动生效 this.posts = postData; } } }
子组件触发事件后,父组件更新本地posts,子组件接收的posts会自动同步更新。
情况2:父组件的posts是上层传来的props
如果posts确实是上层组件传递的props,父组件不能直接修改它,需要向上触发事件通知上层组件更新:
// 父组件代码 export default { props: ['posts'], methods: { removeBlockedUserPosts(blockedUserName) { const postData = this.posts.filter(post => post.userName !== blockedUserName); // 向上层组件触发事件,传递过滤后的数组 this.$emit('update:posts', postData); } } }
上层组件监听事件更新自身数据:
<!-- 上层组件使用当前父组件的代码 --> <parent-component :posts="parentPosts" @update:posts="parentPosts = $event"></parent-component>
也可以用Vue 2的.sync修饰符简化写法:
<parent-component :posts.sync="parentPosts"></parent-component>
为什么不用this.$set?
this.$set主要用于给对象添加新属性,或者修改数组的某个索引值(Vue无法监听数组索引赋值的变化)。而直接替换整个数组是Vue默认支持响应式的,完全没必要额外用this.$set。如果非要用(仅作示例):
this.$set(this, 'posts', postData);
内容的提问来源于stack exchange,提问作者PSA
相关产品推荐
相关产品推荐

