使用react思想搭建vue框架,让vue更加面向对象

114 阅读1分钟

1. React核心思想:

React的哲学以及核心思想是封装组件,各个组件维护自己的状态和UI,当状态变更,自动更新渲染整个组件。

image.png

2. React思想设计vue组件

  • 一个vue组件有且只有一个model,该组件所有的属性全部在这个model上
  • 通过props对这个model的类型进行class限制,让代码更加面向对象

代码实现如下:

<template>
  <div>
    <mt-field :label="model.label" 
              :placeholder="model.placeholder" 
              v-model="model.text" />
  </div>
</template>

<script>
export class InputCellModel {
  constructor() {
    this.text = ""
    this.label = "label"
  }
  
  get placeholder() {
    return `请输入${this.label}`
  }
}

export default {
  props: {
    model: {
      type: Object,
      validator: (value) => value instanceof InputCellModel,
      default: function () {
        return new InputCellModel()
      },
    },
  },
  name: "InputCell",
}
</script>

父组件引用该组件

<template>
  <div class="home">
    <InputCell :model="usernameModel" />
  </div>
</template>

<script>
// @ is an alias to /src
import InputCell, { InputCellModel } from "@/components/InputCell"

export default {
  name: "HomeView",
  components: {
    InputCell,
  },
  data() {
    return {
      usernameModel: new InputCellModel(),
    }
  },
  created() {
    this.usernameModel.label = "用户名"
  },
}
</script>

3. 具体代码实现 github.com/AblerSong/v…

image.png

4. 根据上述思路搭建的前端框架 MVM架构

MVM架构文档

MVM架构代码