初识MVC

123 阅读1分钟

MVC

MVC是做什么

  • M:Model(模型,也就是数据)
  • V:View(视图,面向用户一端)
  • C:Controller(控制器,所有其他操作)
const model = {
    data:{},
    getData(){},
    updateData(){},
    addData(){},
    deleteData(){}
}

const view = {
    template:`<h1>hi</h1>`
    init(){},
    render()
}

const controller = {
    Compute.....
}

EventBus

API:

  • on()
  • off()
  • emit()

例子:

//父组件://创建事件中心
data(){
  return {
    eventBus: new Vue()
  }
},
provide(){
  return {
  eventBus: this.eventBus
  }
}
//子组件://注入事件中心
inject: ['eventBus']

//父子组件之间通信
this.eventBus.$emit() // 发布
this.eventBus.$on() // 订阅
this.eventBus.$off() // 取消订阅

表驱动编程

解决的问题:过多的if-else判断语句,程序代码臃肿

问题: 需要知道一年中每个月有几天

不使用表驱动编程:

if (month === 1) {
    return 31;
}
if (month === 2) {
    return 28;
}
...
if (month === 12) {
    return 31;
}

使用表驱动编程:

const month: number = new Date().getMonth(),
    year: number = new Date().getFullYear(),
    isLeapYear: boolean = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;

const monthDays: number[] = [31, isLeapYear ? 29 : 28, 31, ... , 31];
const days: number = monthDays[month];

模块化

模块化就是让代码各司其职,互不干扰,降低耦合,具体做法暂时由于编码经验不足不能列出。