7

白话说框架

 3 years ago
source link: https://segmentfault.com/a/1190000038248178
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

如果你只会使用 Vue 或者 React,那么这篇文章适合你。

本文不深入聊原理,只对比基础功能的使用,先看下面这份数据,百度搜索指数,很明显 Vue 搜索指数明显高于 React 以及 Angular。

FFZzQfe.jpg!mobile

从简单学起没问题,你以为的技术之路这样的

jaQNJn.jpg!mobile

其实你是这样的

JzAFfyF.jpg!mobile

想想自己除了 Vue, 你还有什么?写此文的目的就是让大家领悟到使用框架的方法和技巧。

下面是截取 react 与 vue 官方文档目录,共通的基础功能至少包含 9 项

  • 数据绑定
  • 模板
  • 条件
  • 列表
  • 表单绑定
  • 事件处理
  • 生命周期
  • 组件

UFbq2eQ.jpg!mobile

以上包含了当下流行框架基本必备功能,先不去想框架具体实现细节,就以上七个功能,在不手动操作 DOM 的情况下如何实现?

三大框架都借助 MVVM 的思想,其优势就是摆脱手动操作 DOM 及节点数据获取带来的低效问题,往下看

MVVM

MVVM 旨在利用数据绑定函数,通过 ViewModal 自动去更新 DOM 的状态,进而从视图层中几乎删除所有 GUI 代码。

Yz2YRbF.jpg!mobile

既然大家都受到 VM 思想的启发,且基础功能都大致相似,我们逐一对比 Vue 及 React 的基础功能

数据绑定

vue 双向绑定,react 单向绑定,代码比较

// vue

// 该对象被加入到一个 Vue 实例中
var vm = new Vue({
  data: { a: 1 },
  created: function () {
    this.a = 2;
  },
});

// react
var data = { a: 1 };
class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    this.state = { a: 1 };
  }

  componentDidMount() {
    // 须通过方法触发
    this.setState({
      a: 2,
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
      </div>
    );
  }
}

ReactDOM.render(<HelloWorld />, document.getElementById("root"));

模板

  • 表达式

    JSX 用 {} ,vue 用 {{}} , 代码比较

    // vue
    <template>
        <div>
            <span>{{name}}</span>
            <span>{{name + 'abc'}}</span>
            <span>{{`${name}abc`}}</span>
            <span>{{isShow?'abc':'efg'}}</span>
            <span>{{()=>{return 'abc'})}}</span>
        </div>
    </template>
    
    // react
    <div>
        <span>{name}</span>
        <span>{name + 'abc'}</span>
        <span>{`${name}abc`}</span>
        <span>{isShow?'abc':'efg'}</span>
        <span>{()=>{return 'abc'})}</span>
    </div>
  • 指令

    vue 指令 v-ifv-else-ifv-elsev-showv-modal
    react 无指令

    代码比较

    // vue
      <template>
          <div>
              <p v-if="isA">我是A</p>
              <p v-else-if="isB">我是B</p>
              <p v-else>我是C</p>
              <p v-show="isShow">大魔王现世了</p>
              <input type="text" v-model="inputText"/>
              <ul>
                  <li v-for="(item, i) in list" :key="item.id">{{item.text}}</li>
              </ul>
          </div>
      </template>
    
      // react
      <div>
          {
              isA ?
              <p>我是A</p> :
              isB ?
              <p>我是B</p> :
              <p>我是C</p>
          }
          <p style={{display: isShow ? 'block' : 'none'}}>大魔王现世了</p>
          <input type="text" onChange={val => () => {this.setState({inputText:val})}
              value={this.state.inputText}/>
          <div className='btn' style={{marginLeft:'10px'}}></div>
          <ul>
              {
                  list.map((item, i) => <li key={item.id}>{item.text}</li>)
              }
          </ul>
      </div>

    有没有发现 react 中透漏着表达式的芬芳,这也是我个人喜欢 react 的原因

  • 属性

    绑定也就相当于组件传参,方便把需要自定义的参数传递到子组件中,常见的绑定有:属性绑定、class、style

    代码比较

    // vue
    
      // 仔细看了文档才看懂什么意思,active 是 class, isActive是判断条件,
      <div v-bind:class="{ active: isActive }"></div>
      <div
          class="static"
          v-bind:class="{ active: isActive, 'text-danger': hasError }"
      ></div>
      <div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
      // react
      <div className={`static ${isActive?:'active':''}`}></div>
      <div style={{color: activeColor, fontSize: fontSize + 'px'}}></div>

    细品,表达式的芬芳

表单绑定

vue 用 v-modal ,react 用 onChange , 代码比较

// vue
<input v-model="userName" />
<input v-bind:value="userName" v-on:input="userName = $event.target.value" />
第一行的代码其实只是第二行的语法糖。input 元素本身有个 oninput事件,这是 HTML5
新增加的,类似 onchange ,每当输入框内容发生变化,就会触发 oninput。

// react
<input value={userName} onChange={($event=>this.setState({userName:
$event.target.value}))}>

事件处理

vue 通过 v-on:* ,react 通过 on* , 代码比较

// vue
<div id="example-2">
  <!-- `greet` 是在下面定义的方法名 -->
  <button v-on:click="greet">Greet</button>
</div>

var example = new Vue({
  el: "#example",
  data: {
    name: "Vue.js",
  },
  // 在 `methods` 对象中定义方法
  methods: {
    greet: function (event) {
      // `this` 在方法里指向当前 Vue 实例
      alert("Hello " + this.name + "!");
      // `event` 是原生 DOM 事件
      if (event) {
        alert(event.target.tagName);
      }
    },
  },
});

//react
class example extends Component {
  constructor(props) {
    super(props);
    this.state = { name: "React.js" };
  }

  greet(event) {
    // `this` 在方法里指向当前 Vue 实例
    alert("Hello " + this.state.name + "!");
    // `event` 是原生 DOM 事件
    if (event) {
      alert(event.target.tagName);
    }
  }
  render() {
      <button onClick={this.greet}>Greet</button>
  }
}

生命周期

生命周期的存在,也是为了在合适的时机执行各自的操作,再加上使用 virtual DOM 的机制,需要把握好组件挂载的时机,生命周期钩子就显得非常有必要了。

不管是 vue 还是 react,生命周期都会经历以下阶段:

  • 初始化阶段
  • 运行阶段
  • 销毁阶段

vue

iY7FRnB.jpg!mobile

react(v16.3 版本之前,之后版本生命周期有所调整)

zeiUnqu.jpg!mobile

组件

组件的复用的高效不言而喻,组件设计、组件划分,也是一门学问

vue 组件的介绍,花样很多

nuAzEn3.jpg!mobile

react 组件

qyQRzeV.jpg!mobile

总结

通过对两大框架基础功能的对比,不难发现实现思路大同小异,只是在细节上各有各的考虑,其中 Vue 自定义了很多 api,而 react 则通过表达式玩出了新花样,跳出框架本身,相信你对前端框架会看的更加透彻。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK