来自 Redux 文档 https://user-gold-cdn.xitu.io/2018/5/2/1631f590aa5512b7
用 容器组件/展示组件 模式改造上面的例子
针对最初的例子,如何快速按照这种模式来划分组件呢?我们主要针对 CommentList.vue 进行拆分,首先是基本的概要设计:
概要设计
展示组件
components/CommentListNew.vue 这是一个新的评论展示组件,用于展示评论
comments: Array prop 接收以 { id, author, body } 形式显示的 comment 项数组。
fetch() 接收更新评论数据的方法
展示组件只定义外观并不关心数据来源和如何改变。传入什么就渲染什么。
comments、fetch 等这些 props 并不关心背后是否是由 Vuex 提供的,你可以使用 Vuex,或者其他状态管理库,甚至是一个 EventBus,都可以复用这些展示组件。
同时,可以利用 props 的类型和验证来约束传入的内容,比如验证传入的 comments 是否是一个含有指定字段的对象,这在之前混合组件的情况是下是没有的,提高了代码的健壮性。
容器组件
containers/CommentListContainer.vue 将 CommentListNew 组件连接到 store
容器组件可以将 store 对应的 state 或者 action 等封装传入展示组件。
编码实现
Talk is cheap, show me the code!
components/CommentListNew.vue
这个文件不再依赖 store,改为从 props 传递。
值得注意到是 comments 和 fetch 分别定义了 type 、default 和 validator,用以定义和验证 props。
<template>
<ul>
<li v-for="comment in comments"
:key="comment.id"
>
{{comment.body}}—{{comment.author}}
</li>
</ul>
</template>
<script>
export default {
name: 'CommentListNew',
props: {
comments: {
type: Array,
default () {
return []
},
validator (comments) {
return comments.every(comment =>
'body' in comment &&
'author' in comment &&
'id' in comment
)
}
},
fetch: {
type: Function,
default: () => {}
}
},
mounted () {
this.fetch()
}
}
</script>
containers/CommentListContainer.vue
容器组件的职责
通过 computed 来获取到状态更新,传递给展示组件
通过 methods 定义回调函数,回调函数内部调用 store 的 dispatch 方法,传递给展示组件
<template>
<CommentList
:comments="comments"
:fetch="fetchComments"
></CommentList>
</template>
<script>
import CommentList from '@/components/CommentListNew'
export default {
name: 'CommentListContainer',
components: {
CommentList
},
computed: {
comments () {
return this.$store.state.comments
}
},
methods: {
fetchComments () {
return this.$store.dispatch('fetchComments')
}
}
}
</script>
内容版权声明:除非注明,否则皆为本站原创文章。
