Model
层: 对应数据层的域模型(融合了行为和数据的域的对象模型), 主要做域模型的同步。
通过Ajax/fetch等API完成客户端和服务端业务Model的同步。在层间关系里,主要用于抽象出- ViewModel中视图的Model。
View
层: 作为视图模板存在,在整个MVVM里,整个View是一个动态模板。
除了定义结构、布局外,它展示的是ViewModel层的数据和状态。
View层不负责处理状态,View层做的是数据绑定的声明、指令的声明、事件绑定声明。
ViewModel
层: 把View需要的层数据暴露,并对View层的数据绑定声明、指令声明、事件绑定声明负责。
也处理View层的具体业务逻辑。ViewModel底层会做好绑定属性的监听。
当ViewModel中数据发生变化,View 层会得到更 新;⽽当 View中声明了数据的双向绑定(通常是表单元素),框架也会监听View 层(表单)值的变化。
⼀旦值变化,View层绑定的 ViewModel中的数据也会得到⾃动更新。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<div class="add">
用户名称:
<input type="text" v-model="name">
<input type="button" value="添加" @click="addUser(this.name)">
</div>
<table border="1">
<tr v-if="users.length===0">
<td colspan="4">没有品牌数据</td>
</tr>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>date</th>
</tr>
</thead>
<tr v-for="user in users">
<td> {{user.id}}</td>
<td>{{user.name}}</td>
<td> {{user.date}}</td>
<td><a @click.prevent="deleteUser(user.id)" href="#">删除</a></td>
</tr>
</table>
</div>
<script>
new Vue({
el: '#app',
data: {
name:'',
maxId:3,
users: [{
id:1,
name: 'LV',
date: '2018-8-1'
}, {
id:2,
name: 'Lenovo',
date: '2018-8-1'
}, {
id:3,
name: 'TCL',
date: '2018-8-1'
}
],
},
methods: {
//delete是vue的关键字,不能用作方法名
deleteUser: function (id) {
if (confirm("是否删除")) {
this.users.splice(id, 1)
}
},
addUser: function (name) {
console.log('add方法被调用');
this.maxId++;
const user = {
id : this.maxId,
name: this.name,
date: new Date()
};
this.users.push(user) //unshif(user) 向数组开头添加数据;
}
}
});
</script>
</body>
</html>
length 设置或返回数组元素的个数。 length 属性可设置或返回数组中元素的数目。
Arrays 方法
push
() 向数组的末尾添加一个或更多元素,并返回新的长度。
pop
() 删除数组的最后一个元素并返回删除的元素。
unshift
() 向数组的开头添加一个或更多元素,并返回新的长度。
shift
() 删除并返回数组的第一个元素。