search
HomeWeb Front-endJS TutorialWhat are the methods for React to introduce container components to Vue?

This time I will introduce to you what methods React can introduce container components to Vue, and what are the precautions for React to introduce container components to Vue. Here are practical cases, let’s take a look.

If you have used Redux to develop React, you must have heard of container components (Smart/Container Components) or presentation components (Dumb/Presentational Components). What are the benefits of this division? Can we learn from this? What are the different ways to write Vue code? This article will demonstrate why we should adopt this pattern and how to write both components in Vue.

Why use container components?

If we want to write a component to display comments, before we have heard of container components, our The code is generally written like this:

components/CommentList.vue

<template>
 <ul>
 <li>
  {{comment.body}}—{{comment.author}}
 </li>
 </ul>
</template>
<script>
export default {
 name: &#39;CommentList&#39;,
 computed: {
 comments () {
  return this.$store.state.comments
 }
 },
 mounted () {
 this.$store.dispatch(&#39;fetchComments&#39;)
 }
}
</script>

store/index.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
 state: {
 comments: [],
 },
 mutations: {
 setComments(state, comments) {
  state.comments = comments;
 },
 },
 actions: {
 fetchComments({commit}) {
  setTimeout(() => {
  commit('setComments', [
   {
   body: '霸气侧漏',
   author: '雷叔',
   id: 1123,
   },
   {
   body: '机智如我',
   author: '蕾妹',
   id: 1124,
   },
  ]);
  });
 },
 },
});

export default store;

It seems natural to write it this way. Are there any problems or areas that can be optimized?

There is an obvious problem. Since CommentList.vue is coupled with the Vuex store of the project, it is difficult to reuse it without the current project.

Is there a better way to organize components that can solve this problem? It’s time to understand the concept of container components in the React community.

What is a container component

In React.js Conf 2015, there is a topic of Making your app fast with high-performance components introduced Container component.

The container component is specifically responsible for communicating with the store and passing data to the ordinary display component through props. If the display component wants to initiate an update of data, it also passes it through the container component through props. The Callback function is used to tell the store.

Since the display component is no longer directly coupled with the store, but defines the data and methods it needs through the props interface, the reusability of the display component will be higher.

The difference between container components and display components

##FunctionDescribe how to display (skeleton, style)Describe how to run (data acquisition, status update)Use store directlyNoYesData sourcepropsListen to store stateData modificationCall callback function from propsDispatching actions to store

来自 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>
  {{comment.body}}—{{comment.author}}
 </li>
 </ul>
</template>
<script>
export default {
 name: &#39;CommentListNew&#39;,
 props: {
 comments: {
  type: Array,
  default () {
  return []
  },
  validator (comments) {
  return comments.every(comment =>
   &#39;body&#39; in comment &&
   &#39;author&#39; in comment &&
   &#39;id&#39; in comment
  )
  }
 },
 fetch: {
  type: Function,
  default: () => {}
 }
 },
 mounted () {
 this.fetch()
 }
}
</script>

containers/CommentListContainer.vue

容器组件的职责

通过 computed 来获取到状态更新,传递给展示组件

通过 methods 定义回调函数,回调函数内部调用 store 的 dispatch 方法,传递给展示组件

<template>
 <commentlist></commentlist>
</template>
<script>
import CommentList from &#39;@/components/CommentListNew&#39;
export default {
 name: &#39;CommentListContainer&#39;,
 components: {
 CommentList
 },
 computed: {
 comments () {
  return this.$store.state.comments
 }
 },
 methods: {
 fetchComments () {
  return this.$store.dispatch(&#39;fetchComments&#39;)
 }
 }
}
</script>

使用 @xunlei/vuex-connector 实现容器组件

上面演示的容器组件的代码非常简单,实际上如果直接投入生产环境,会产生一些问题。

手动实现容器组件存在的不足

代码比较繁琐

在上面的例子中,每次传递一个 state 都要定义一个 computed,每传递一个 mutation 或者 action 都需要定一个方法,而且还要注意这个方法的参数要透传过去,同时还要处理返回值,比如异步的 action 需要返回 promise 的时候,定义的这个 method 也得把 action 的返回值返回出去。

无法透传其他 props 给展示组件

比如展示组件新增了一个 prop 叫做 type,可以传递一个评论的类型,用来区分是热门还是最新,如果用上面的容器实现方式,首先需要在容器组件这层新增一个 prop 叫做 type 接受外部传来的参数,然后在展示组件内部同样定义一个 叫做 type 的 prop,然后才能传递下去。

需要透传的 prop 必须定义两遍,增加了维护的成本。

<commentlistcontainer></commentlistcontainer>
<commentlist></commentlist>

容器组件无法统一进行优化

每一个手动实现的容器组件实质上代码逻辑非常近似,但是没有经过同一层封装,如果目前实现的容器组件存在一些性能优化的地方,需要每个容器组件都进行统一的修改。

无法控制展示组件不去获取 store

因为容器组件是通过 this.$store 获取 store 的,展示组件内部实质上也可以直接跟 store 通信,如果没有约束,很难统一要求展示组件不得直接和 store 通信。

使用 @xunlei/vuex-connector

@xunlei/vuex-connector 借鉴了 react redux 的 connect 方法,在 vuex 基础上进行的开发。

有以下几个特点:

代码非常简洁

下面是上面例子中手动实现的容器组件的改造版本:

comonents/ConnectCommentListContainer.vue

<script>
import CommentListNew from &#39;@/components/CommentListNew&#39;
import { connector } from &#39;@/store&#39;
export default connector.connect({
 mapStateToProps: {
  comments: (state) => state.comments
 },
 mapActionToProps: {
  fetch: &#39;fetchComments&#39;
 }
})(CommentListNew)
</script>

通过 connector 的 connnect 方法,传入要映射的配置,支持 mapStateToProps, mapGettersToProps, mapDispatchToProps, mapCommitToProps 这四种,每一种都是只要配置一个简单的 map 函数,或者字符串即可。

然后在返回的函数中传入要连接的展示组件,是不是非常的简洁,同时借鉴了 redux 优雅的函数式风格。

问题来了,connector 是什么?

connector 实际上是一个能获取到 store 实例的连接器,可以在初始化 vuex store 的时候进行初始化。

import Vue from 'vue';
import Vuex from 'vuex';
import VuexConnector from '@xunlei/vuex-connector';
Vue.use(Vuex);
const store = new Vuex.Store({
 // your store
});
export const connector = new VuexConnector(store);
export default store;

一个 Vue 程序实际上只需要初始化一次即可。

支持透传其他 props 给展示组件

VuexConnector 实现的时候采用了函数式组件( functional: true )

函数式组件是无状态 (没有响应式数据),无实例 (没有 this 上下文)。

在作为包装组件时函数式组件非常有用,比如,当你需要做这些时:

程序化地在多个组件中选择一个

在将 children, props, data 传递给子组件之前操作它们。

另外,函数式组件只是一个函数,所以渲染开销也低很多。然而,对持久化实例的缺乏也意味着函数式组件不会出现在 Vue devtools 的组件树里。

因此需要透传的 props 可以直接透传,需要通过 map 方式从 store 里进行获取的 props 直接会根据配置生成。

统一封装方便后续统一优化

VuexConnector.connect 方法将本来需要重复做的事情进行了抽象,也带来了后期进行统一优化和升级的便利。

可以控制展示组件无法直接与 store 通信

VuexConnector 不依赖 this.$store,而是依赖初始化传入的 store 实例,容器组件可以用 connect 将展示组件与 store 进行连接。

由于不依赖 this.$store,我们在程序入口 new Vue 的时候,就不需要传入 store 实例了。

比如,之前我们是通过下面的方式进行初始化:

import Vue from 'vue';
import App from './App';
import store from './store';
new Vue({
 el: '#app',
 components: {App},
 template: '<app></app>',
 store,
});

使用了 VuexConnector 之后,在最初 new Vue 的时候就不需要也最好不要传递 store 了,这样就避免了 this.$store 泛滥导致代码耦合的问题。

引入容器组件/展示组件模式带来的好处

可复用性

容器组件/展示组件的划分,采用了单一职责原则的设计模式,容器组件专门负责和 store 通信,展示组件只负责展示,解除了组件的耦合,可以带来更好的可复用性。

健壮性

由于展示组件和容器组件是通过 prop 这种接口来连接,可以利用 props 的校验来增强代码的可靠性,混合的组件就没有这种好处。

另外对 props 的校验可以采取一下几种方式:

Vue 组件 props 验证

可以验证 props 的类型,默认可以校验是否是以下类型:

  • String

  • Number

  • Boolean

  • Function

  • Object

  • Array

  • Symbol

如果你的 props 是类的一个实例,type 也可以是一个自定义构造器函数,使用 instanceof 检测。

如果还是不满足需求,可以自定义验证函数:

// 自定义验证函数
propF: {
 validator: function (value) {
  return value > 10
 }
}

TypeScript 类型系统

Vue 组件 props 验证对于对象或者其他复杂的类型校验还是不太友好,所以很多人也推荐大家的 props 尽量采取简单类型,不过如果你有在用 TypeScript 开发 Vue 应用,可以利用 TypeScript 静态类型检查来声明你的 props 。

@Component
export default class Hello extends Vue {
 @Prop
 info: IHelloInfo; // 这里可以用你自定义的 interface
}

可测试性

由于组件做的事情更少了,使得测试也会变得容易。

容器组件不用关心 UI 的展示,只关心数据和更新。

展示组件只是呈现传入的 props ,写单元测试的时候也非常容易 mock 数据层。

引入容器组件/展示组件模式带来的限制

学习和开发成本

因为容器组件/展示组件的拆分,初期会增加一些学习成本,不过当你看完这篇文章,基本上也就入门了。

在开发的时候,由于需要封装一个容器,包装一些数据和接口给展示组件,会增加一些工作量, @xunlei/vuex-connector 通过配置的方式可以减轻不少你的工作量。

另外,在展示组件内对 props 的声明也会带来少量的工作。

总体来说,引入容器组件/展示组件模式投入产出比还是比较值得的。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Node.Js实现端口重用步骤详解

Vue.js双向绑定实现步骤说明


Display component
Container component

The above is the detailed content of What are the methods for React to introduce container components to Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment