Vue初体验
案例一:展示动态数据
vue
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script src="./lib/vue.js"></script>
<script>
// 通过引入的文件,创建Vue对象
const app = Vue.createApp({
// 利用插值语法将data中设置的变量展示到页面中
template: `<h2>{{message}}</h2>`,
// 参数
data: function() {
return {
message: "Hello Vue"
}
}
})
// 将对象挂在到id=app的组件上
app.mount("#app")
</script>
<!-- <script>
const app = Vue.createApp({
// 插值语法: {{title}}
template: `<h2>{{message}}</h2>`,
data: function() {
return {
title: "Hello World",
message: "你好啊, Vue3"
}
}
})
app.mount("#app")
</script> -->
</body>
</html>
案例二:展示数组
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script src="./lib/vue.js"></script>
<script>
// 通过引入的文件,创建Vue对象
const app = Vue.createApp({
// 利用插值语法将data中设置的变量展示到页面中
template: `<h2>{{message}}</h2>`,
// 参数
data: function() {
return {
message: "Hello Vue"
}
}
})
// 将对象挂在到id=app的组件上
app.mount("#app")
</script>
<!-- <script>
const app = Vue.createApp({
// 插值语法: {{title}}
template: `<h2>{{message}}</h2>`,
data: function() {
return {
title: "Hello World",
message: "你好啊, Vue3"
}
}
})
app.mount("#app")
</script> -->
</body>
</html>
案例三:计数器
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h2>当前计数:{{count}}</h2>
<!-- 绑定方法 -->
<button @click="sub">-1</button>
<button @click="add">+1</button>
</div>
<!-- 引入vue -->
<script src="./lib/vue.js"></script>
<script>
const app = Vue.createApp({
data: function() {
return {
count: 0
}
},
// 创建methods方法集合
methods: {
add() {
this.count++;
},
sub() {
this.count--;
}
}
})
app.mount("#app")
</script>
</body>
</html>
声明式和命令式
命令式编程关注的是 "how to do"自己完成整个how的过程:不如JavaScript 声明式编程程关注的是 "what to do",由框架(机器)完成 "how"的过程
MVVM模型
早期MVC是常使用的架构模式
- Model:管理数据及业务逻辑。
- View:负责界面展示。
- Controller:接收用户输入,协调 Model 和 View 的交互。
MVC里,Model处理数据,View显示界面,Controller作为中间层处理逻辑。用户交互会先到Controller,然后更新Model,再通知View更新。但有时候,View和Model之间可能会有直接的联系,特别是在一些框架里
现在最常用的架构模式是mvvm
- Model:数据层,与 MVC 类似。
- View:纯 UI 展示,不处理逻辑。
- ViewModel:代替 Controller,将 Model 数据转换为 View 可用的形式(通过数据绑定),并处理业务逻辑。
Model和View还是类似的角色,但ViewModel取代了Controller的位置。ViewModel负责将Model的数据转换成View能直接显示的形式,并且通过数据绑定自动同步,比如使用双向绑定技术。这样的话,View和ViewModel之间的交互更自动化,减少了样板代码,View层会更被动,只负责显示数据,而业务逻辑都在ViewModel里处理。
data属性
存放在data中的数据将会被Vue的响应式系统劫持,之后对该对象的修改或者访问都会在劫持中被处理:
methods
methods属性是一个对象,通常我们会在这个对象中定义很多的方法;这些方法可以被绑定到 模板中;在该方法中,我们可以使用this关键字来直接访问到data中返回的对象的属性;