为什么要使用前端框架?
保持UI和状态同步。
当前前端主流框架:
①:React:
优点:虚拟DOM;更加轻量;JSX语法;Facebook支持;
缺点:官方文档没有体系化;JSX语法;
②:Angular(MVVM模式)
优点:MVVM模式;双向数据绑定;依赖注入
缺点:语法复杂,使用typescrip;没有向后兼容;
③:Vue
优点:使用HTML模板;详细文档并且中文化;30kb;
缺点:没有大厂支持;缺乏大型项目支持;
使用原生JS实现demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#app {
width: 200px;
height: 200px;
box-shadow: 0 0 20px #ccc;
}
#num {
display: block;
width: 200px;
height: 100px;
line-height: 100px;
text-align: center;
font-size: 80px;
}
.btn {
width: 100px;
height: 100px;
font-size: 80px;
font-weight: lighter;
border: none;
outline: none;
cursor: pointer;
}
#decrease {
background-color: #DBB371;
}
#increase {
background-color: #1d1b1c;
color: #ccc;
}
.btn-wrapper {
font-size: 0;
}
</style>
</head>
<body>
<div id="app">
<span id="num">0</span>
<div class="btn-wrapper">
<button class="btn" id="decrease">-</button>
<button class="btn" id="increase">+</button>
</div>
</div>
<script>
//数据层面和视图层面的代码耦合了
//视图层面
const num = document.getElementById('num');
const decrease = document.getElementById('decrease');
const increase = document.getElementById('increase');
//数据层面
let val = 0; //初始化值
decrease.onclick = function() {
//数据层面
val--;
//视图层面
num.innerText = val;
}
increase.onclick = function() {
//数据层面
val++;
//视图层面
num.innerText = val;
}
</script>
</body>
</html>
实现效果:
Model & View
Model:Model层用于封装和应用程序的业务逻辑相关的数据以及对数据的处理方法。
View:View作为视图层,主要负责数据的展示。
将数据层和视图层分开:(将JavaScript改写为:)
<script>
const myApp = {};
//Model主管数据层面的操作
myApp.Model = function() {
let val = 0;
this.add = function() {
val++;
}
this.minus = function() {
val--;
}
this.getVal = function() {
return val; //返回val值,便于外界获取val值
}
}
//View主管视图层面的操作
myApp.View = function() {
const num = document.getElementById('num');
const decrease = document.getElementById('decrease');
const increase = document.getElementById('increase');
this.render = function(model) {
num.innerText = model.getVal();
}
}
const model = new myApp.Model();
const view = new myApp.View();
model.add();
model.add();
model.add();
model.minus();
console.log(model.getVal());
view.render(model);
</script>
//结果为2