Skip to content

组件化

仲灏约 1 分钟

组件化

组件化基础

web 开发的历史中,组件化其实很早就有了,在 jsp asp 就有了。

ejs 组件 —— 可以看《koa2 微博》课程的示例

vue 组件

html
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

React 组件

js
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <HelloWorld msg="Welcome to Your React App"/>
      </header>
    </div>
  );
}

数据驱动视图

ejs 组件

可以看《koa2 微博》课程的示例 【注意】ejs 这种服务端渲染,有一个问题:不能动态改变,只能根据 props 静态渲染。 因此需要 vue 和 React

vue —— MVVM 模型

(参考 vue 的 MVVM 模型图)

html
<template>
  <div id="app">
    <p @click="changeName">{{name}}</p>
    <ul>
        <li v-for="(item, index) in list" :key="index">
            {{item}}
        </li>
    </ul>
    <button @click="addItem">添加一项</button>
  </div>
</template>

<script>
export default {
  name: 'app',
  data() {
      return {
        name: 'vue',
        list: ['a', 'b', 'c']
      }
  },
  methods: {
    changeName() {
        this.name = '双越'
    },
    addItem() {
        this.list.push(`${Date.now()}`)
    }
  }
}
</script>

React —— setState 方式

js
class List extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            name: 'React',
            list: ['a', 'b', 'c']
        }
    }
    render() {
        return <div>
            <p onClick={this.changeName.bind(this)}>{this.state.name}</p>
            <ul>{
                this.state.list.map((item, index) => {
                    return <li key={index}>{item}</li>
                })
            }</ul>
            <button onClick={this.addItem.bind(this)}>添加一项</button>
        </div>
    }
    changeName() {
        this.setState({
            name: '双越'
        })
    }
    addItem() {
        this.setState({
            list: this.state.list.concat(`${Date.now()}`) // 使用不可变值
        })
    }
}

vue 和 React 对比

都支持组件化,没有啥区别。(在这一点和 ejs 也没啥区别)

数据驱动视图

  • vue 声明式
  • React 函数式

上次更新:

讨论区

欢迎留下想法与补充