前言
首先,为什么我需要做这个项目准备工作呢?因为常年习惯React开发的我,最近突然接手了一个Vue项目,而之前基本没有过Vue的实践,这么突兀让还在沉溺于React开发的我进行Vue开发,甚是不习惯,那自然我需要想办法让Vue开发尽量与React相似,这样大概让自己在开发过程中更得心应手吧。
组件开发
特性对比
众所周知,Vue和React都有那么一个特性,那就是可以让我们进行组件化开发,这样可以让代码得到更好的重用以及解耦,在架构定位中这个应该叫纵向分层吧。但是,两个框架开发组件的写法都有所不同(这个不同是基于我的开发习惯),下面先看一下不同的地方。
首先是React,个人习惯于es6的写法(从来没用过es5的createClass的写法):
import React, { Component } from 'react';import propTypes from 'prop-types';export default class Demo extends Component { state = { text: 'hello world' }; static propTypes = { title: PropTypes.String } static defaultProps = { title: 'React Demo' } setText = e => { this.setState({ text: '点击了按钮' }) } componentWillReveiveProps(nextProps) { console.log(`标题从 ${this.props.title} 变为了 ${nextProps.title}`) } render() { const { title } = this.props; const { text } = this.state; return <div> <h1>{title}</h1> <span>{text}<span> <button onClick={this.setText}>按钮<button> </div> }}
下面是常见vue的写法:
<template> <div> <h1>{{title}}</h1> <span>{{text}}<span> <button @click="setText">按钮</button> </div></template><script>export default { props: { title: { type: String, default: 'Vue Demo' } }, watch: { title(newTitle, oldTitle) { console.log(`标题从 ${oldTile} 变为了 ${newTitle}`) } }, data() { return { text: 'hello world' } }, methods: { setText(e) { this.text = '点击了按钮'; } }}</script>
这里的视图渲染我们先忽略,下一节在详细对比。
prop对比:
Vue的prop必须在props字段里声明。React的prop不强制声明,声明时也可以使用prop-types对其声明约束。 Vue的prop声明过后挂在在组件的this下,需要的时候在this中获取。React的prop存在组件的props字段中,使用的时候直接在this.props中获取。组件状态对比,Vue为data,React为state:
Vue的状态data需要在组件的data字段中以函数的方式声明并返回一个对象。React的状态state可以直接挂载在组件的state字段下,在使用之前初始化即可。 Vue的状态data声明后挂在在this下面,需要的是时候在this中获取。React的状态state存在组件的state字段中,使用的时候直接在this.state中获取。 Vue的状态更新可以直接对其进行赋值,视图可以直接得到同步。React的状态更新必须使用setState,否则视图不会更新。新闻热点
疑难解答
图片精选