当前 Vue 的最新稳定版本是 v3.4.35,而Vue 2 已于 2023 年 12 月 31 日停止维护。
Vue2的书写风格是选项式 API ,而Vue3的书写风格同时支持选项式API和组合式 API。那我们选哪一种风格的API来学习呢?我建议先学习选项式API,然后再学习组合式API。学习选项式API,既是能写Vue3,用能看懂Vue2,毕竟Vue2的项目现在也还挺多的。而且学会了选项式API,再学组合式API也是很简单的,并不会花很多时间。这样不是也挺好的吗?
下面开始今天的学习吧。
1、第一个Vue程序
创建一个Vue程序需要以下几个步骤:
1.1导入开发版本的Vue.js
如果再html文件中使用Vue.js,可以如下方式导入:
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
复制
也可以把vue.js下载到本地与html文件同一目录,然后在script标签内导入:
<script src="./vue2.js"></script>
复制
1.2创建Vue实例对象, 设置el属性和data属性
var app = new Vue({ el:"#app", // 指定挂载点 data:{ message:"Hello, Vue!" // 定义数据 } })
复制
el:挂载点
- el是用来设置Vue实例挂载(管理)的元素
- Vue会管理el选项命中的元素及其内部的后代元素
- 可以使用其他的选择器,但是建议使用ID选择器
- 可以使用其他的双标签,不能使用HTML和BODY
data:数据对象
- Vue中用到的数据定义在data中
- data中可以写复杂类型的数据(如对象、数组等)
例如:
data:{ message:"Hello, Vue!", array:["JAVA","C#","Python"], // 数组 obj:{ // 对象 name:"zhangsan", age:20 } }
复制
- 渲染复杂类型数据时,遵守js的语法即可
1.3使用简洁的模板语法把数据渲染到页面上
<div id="app"> {{ message }} </div>
复制
1.4完整的html代码
包含上述3步的完整的html文件如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue Rendering Example</title> <!-- 引入Vue.js文件 --> <script src="./vue2.js"></script> </head> <body> <div id="app"> <!-- 使用插值渲染数据 --> <h1>{{ message }}</h1> </div> <script> // 创建Vue实例 new Vue({ el: '#app', // 指定挂载点 data: { message: 'Hello, Vue!' // 定义数据 } }); </script> </body> </html>
复制
如果是使用Vue3,html文件如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue3 Rendering Example</title> <!-- 引入Vue.js文件 --> <script src="./vue3.js"></script> </head> <body> <div id="app"> <!-- 使用插值渲染数据 --> <h1>{{ message }}</h1> </div> <script> //Vue3需要使用createApp方法 //第1种写法 //const {createApp} = Vue //const app = createApp({ // 代码 // }) //下面使用的是第2种写法: const app = Vue.createApp({ data() { return { message:'Hello,Vue!' } } }) app.mount('#app') </script> </body> </html>
复制
2、Vue指令
Vue指令指的是,以v-开头的一组特殊语法
2.1 v-text指令
v-text指令的作用是:设置标签的内容(textContent)
例如:在javascript脚本中输入:
var app = new Vue({ el:"#app", data:{ message:"Hello" } })
复制
如果在h2标签内使用v-text=“message+’!’”,就是把h2的内容设置为message变量的内容加一个叹号。也可以使用差值表达式{{}}(两个大括号)替换指定内容,即使用{{ message + "! "}}达到一样的效果。
即:
<div id="app"> <h2 v-text="message+’!’"></h2> <h2>{{ message + "! "}}</h2> </div>
复制
页面就会显示:
提示:内部支持写表达式
2.2 v-html指令
v-html指令的作用是:设置元素的innerHTML,内容中有html结构会被解析为标签。
而v-text指令无论内容是什么,只会解析为文本。
提示:解析文本使用v-text,需要解析html结构使用v-html
例如:
var app = new Vue({ el:"#app", data:{ content:"<a href='#'>百度</a>" } })
复制
<div id="app"> <p v-html='content'></p> </div>
复制
页面显示:
2.3 v-on指令
v-on指令的作用是:为元素绑定事件。
事件名不需要写on,比如想在on-click事件上绑定事件写成:v-on:click=“doIt"即可。
指令可以简写为@,比如v-on:click可以写成**@click**。
绑定的方法定义在Vue对象的methods属性中。
例如:
<div id="app"> <input type="button" value="事件绑定" v-on:click=“doIt"> <input type="button" value="事件绑定" v-on:monseenter=“doIt"> <input type="button" value="事件绑定" v-on:dblclick=“doIt"> <input type="button" value="事件绑定" @dblclick=“doIt"> </div>
复制
var app = new Vue({ el:"#app", methods:{ doIt:function(){ // 逻辑 } } })
复制
方法内部通过this关键字可以访问定义在data中数据。
例如:
var app = new Vue({ el:"#app", data:{ message:'Hello!' } methods:{ doIt:function(){ console.log(this.message) } } })
复制
v-on绑定的事件也可以传递参数,比如通过下面的方式传递了两个参数p1和p2。
<input type=“button” @click=“doIt(p1,p2)” />
在Vue的可以通过以下方式接收参数:
var app = new Vue({ el: "#app", methods: { doIt: function(p1,p2) { //doIt方法逻辑 } } })
复制
高阶用法:
事件的后面跟上 .修饰符 可以对事件进行限制
比如加上“.enter” 可以限制触发的按键为回车
事件修饰符有多种
比如下面的例子,只有在输入框输入回车时就会调用sayHi方法。
<input type=“text” @keyup.enter=“sayHi”>
methods:{ sayHi:function(){ console.log('Hi') } }
复制
2.4 v-show指令
v-show指令的作用是:根据真假切换元素的显示状态
例如先在Vue对象里定义数据,isShow值为布尔值false,age值为数字16。
var app = new Vue({ el:"#app", data:{ isShow:false, age:16 } })
复制
在div标签里,定义了三个img,第一个使用v-show=“true”,第二个使用isShow这个定义的数据让v-show=‘isShow’,第三个使用一个表达式age>=18让v-show=“age>=18”。
<div id="app"> <img src="地址" v-show="true"> <img src="地址" v-show="isShow"> <img src="地址" v-show="age>=18"> </div>
复制
这三个img标签,第一个v-show的值为true,所以会显示,第二个值是isShow的值为false,所以img不会显示,第三个由于表达式最终值为false,所以第三个img标签也不会显示。
v-show作用的原理是修改元素的display,实现显示隐藏
指令后面的内容,最终都会解析为布尔值
值为true元素显示,值为false元素隐藏
数据改变之后,对应元素的显示状态会同步更新,并不需要写代码让组件显示还是隐藏,从而达到响应式效果
2.5 v-if指令
v-if指令的作用是:根据表达式的真假切换元素的显示状态
现在Vue中定义一个数据isShow,值为false。
var app = new Vue({ el:"#app", data:{ isShow:false, age:16 } })
复制
在div标签中增加三个p标签,分别通过v-if指令来控制p的显示 还是隐藏。v-if的赋值同样可以直接使用true或false布尔值,可以使用布尔值的数据,还可以使用一个最终值为布尔值的表达式。
<div id="app"> <p v-if="true">我是一个p标签</p> <p v-if="isShow">我是一个p标签</p> <p v-if="age>=18">我是一个p标签</p> </div>
复制
v-if指令的本质是通过操纵dom元素来切换显示状态
表达式的值为true,元素存在于dom树中,为false,从dom树中移除
v-show和v-if区别
适用场景: 如果需要频繁的切换显示状态使用v-show,反之使用v-if。因为v-show的切换系统消耗更小,它只是通过组件的 display值实现显示还是隐藏,并不需要频繁创建和删除组件,而v-if是通过操作dom元素来实现显示状态的切换,需要不断从dom中创建和移除组件,对系统资源消耗会很大。
2.6 v-bind指令
v-bind指令的作用是:为元素绑定属性(比如:src,title,class)
完整写法是 v-bind:属性名
简写的话可以直接省略v-bind,只保留 :属性名
需要动态的增删class建议使用对象的方式
先准备一些数据:
var app = new Vue({ el:"#app", data:{ imgSrc:"图片地址", imgTitle:"标题", isActive:false } })
复制
使用v-bind指令绑定属性:
<div id="app"> <img v-bind:src= "imgSrc" > <img v-bind:title="imgtitle+’!!!!’"> <img v-bind:class="isActive?'active':''"> <img v-bind:class="{active:isActive}"> </div>
复制
前两个简单不说了,第三个img使用的是三目运算符,意思是当isActive为true时class属性为active,isActive为false时,class为空。第四个img使用的方式是对象的方式,即是使用{}来表示是一个对象,里面active:isActive的意思就是active对isActive为true时才成立,也就达到和第三个一样的效果,但书写更简单!
上述4种方式的简写方式如下:
<div id="app"> <img :src= "imgSrc" > <img :title="imgtitle+’!!!!’"> <img :class="isActive?'active':‘’”> <img :class="{active:isActive}"> </div>
复制
2.7 v-for指令
v-for指令的作用是:根据数据生成列表结构
数组经常和v-for结合使用
语法是:( item,index ) in 数据
举例:
先准备数据,定义了两个变量,一个数字型数据的数组arr,包括5个数字,一个包括2个对象的数组objArr。
new Vue({ el: '#app', // 指定挂载点 data: { arr: [1, 2, 3, 4, 5], objArr: [ { name: "jack" }, { name: "rose" } ] } })
复制
利用v-for显示:
<div id="app"> <ul> <li v-for="(item,index) in arr" :title="item"> {{ index }} - {{ item }} </li> <li v-for="(item,index) in objArr"> {{index}}-{{item.name}} </li> </ul> </div>
复制
第一个li会显示arr的数据,index显示数组的序号0,1,2,3,4,因为arr是简单数据的数组,所以item就会显示arr里的数据1,2,3,4,5。
第二个li会显示objArr的数据,index同样显示0,1,2,3,4,因为objArr是一个包括对象的数组,对象的数据要通过“对象名.属性”来访问数据,所以要用item.name才能取到objArr里的对象的name的值。
效果如下:
提示:
item 和 index 可以结合其他指令一起使用
数组长度的更新会同步到页面上,是响应式的
2.8 v-model指令
v-model指令的作用是便捷的设置和获取表单元素的值(双向数据绑定)
举例:
先在Vue中定义一个变量message,值为Hello。
new Vue({ el: '#app', // 指定挂载点 data:{ message:'Hello' } })
复制
然后在文本输入框中绑定。
<div id="app"> <input type="text" v-model="message"> </div>
复制
绑定后,文本输入框的内容就是 “Hello”。当在javascript脚本中 修改message变量值的时候,文本输入框的内容会随之更改。当文本输入框的内容有变化时,变量message的值也会随着一起变化,这样就不需要脚本去获取值了。这就是双向数据绑定,非常方便。
以上就是比较常用的Vue指令。
下面结合一个小应用再熟悉熟悉Vue的指令吧。
3.开发小小记事本
现在要完成一个小小记事本的应用。如下图:
这个小应用主要的功能有:新增记事内容;删除记事内容;统计 记事的条数;清空所有内容;当内容为空时隐藏最下边的提示。
下面逐一进行分析
3.1 新增
我们需要一个数组来保存记事本的每条内容。当输入一条新内容时,按回车键,内容就应该添加到数组中。实现这个功能的要点主要有:
- 生成列表结构(v-for 数组)
- 获取用户输入(v-model)
- 回车,新增数据(v-on .enter 添加数据)
3.2 删除
当把鼠标移动到某行,这一行就会在右边显示一个X,点击就会把这条 记录删掉。实现这个功能的要点主要有:
- 点击删除指定内容(v-on splice 索引)
3.3 统计
在左下角会时时显示有几条记事内容。实现这个功能的要点有:
- 统计信息个数(v-text length)
3.4 清空
点击右下角的“Clear”,就会清除所有记事内容。实现这个功能的要点有:
- 点击清除所有信息(v-on 清空数组)
3.5 隐藏
如果没有记录,最下边的统计和“Clear”这行就应该隐藏,当有新的记录增加,这行就应该再显示 出来。实现这个功能的要点有:
- 没有数据时,隐藏元素(v-show v-if 数组非空)
3.6总结
这个小应用主要用到了以下知识点:
1、列表结构可以通过v-for指令结合数据生成
2、v-on结合事件修饰符可以对事件进行限制,比如.enter
3、v-on在绑定事件时可以传递自定义参数
4、通过v-model可以快速的设置和获取表单元素的值
5、基于数据的开发方式
3.7 代码
完整代码:
<html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>小小记事本</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <meta name="robots" content="noindex, nofollow" /> <meta name="googlebot" content="noindex, nofollow" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" type="text/css" href="./css/index.css" /> </head> <body> <!-- 主体区域 --> <section id="todoapp"> <!-- 输入框 --> <header class="header"> <h1>小小记事本</h1> <input v-model="inputValue" @keyup.enter="add" autofocus="autofocus" autocomplete="off" placeholder="请输入任务" class="new-todo" /> </header> <!-- 列表区域 --> <section class="main"> <ul class="todo-list"> <li class="todo" v-for="(item,index) in list"> <div class="view"> <span class="index">{{ index+1 }}.</span> <label>{{ item }}</label> <button class="destroy" @click="remove(index)"></button> </div> </li> </ul> </section> <!-- 统计和清空 --> <footer class="footer" v-show="list.length!=0"> <span class="todo-count" v-if="list.length!=0"> <strong>{{ list.length }}</strong> items left </span> <button v-show="list.length!=0" class="clear-completed" @click="clear"> Clear </button> </footer> </section> <!-- 底部 --> <footer class="info"> <p> bjzhang75 @2024 </p> </footer> <!-- 开发环境版本,包含了有帮助的命令行警告 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> var app = new Vue({ el: "#todoapp", data: { list: ["读一本书","看一场电影","睡个懒觉"], inputValue: "" }, methods: { add: function () { this.list.push(this.inputValue); }, remove: function (index) { console.log("删除"); console.log(index); this.list.splice(index, 1); }, clear: function () { this.list = []; } }, }) </script> </body> </html>
复制
CSS文件:
/* ./css/index.css */ html, body { margin: 0; padding: 0; } body { background: #fff; } button { margin: 0; padding: 0; border: 0; background: none; font-size: 100%; vertical-align: baseline; font-family: inherit; font-weight: inherit; color: inherit; -webkit-appearance: none; appearance: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } body { font: 14px "Helvetica Neue", Helvetica, Arial, sans-serif; line-height: 1.4em; background: #f5f5f5; color: #4d4d4d; min-width: 230px; max-width: 550px; margin: 0 auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-weight: 300; } :focus { outline: 0; } .hidden { display: none; } #todoapp { background: #fff; margin: 180px 0 40px 0; position: relative; box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1); } #todoapp input::-webkit-input-placeholder { font-style: italic; font-weight: 300; color: #e6e6e6; } #todoapp input::-moz-placeholder { font-style: italic; font-weight: 300; color: #e6e6e6; } #todoapp input::input-placeholder { font-style: italic; font-weight: 300; color: gray; } #todoapp h1 { position: absolute; top: -160px; width: 100%; font-size: 60px; font-weight: 100; text-align: center; color: rgba(175, 47, 47, .8); -webkit-text-rendering: optimizeLegibility; -moz-text-rendering: optimizeLegibility; text-rendering: optimizeLegibility; } .new-todo, .edit { position: relative; margin: 0; width: 100%; font-size: 24px; font-family: inherit; font-weight: inherit; line-height: 1.4em; border: 0; color: inherit; padding: 6px; border: 1px solid #999; box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2); box-sizing: border-box; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .new-todo { padding: 16px; border: none; background: rgba(0, 0, 0, 0.003); box-shadow: inset 0 -2px 1px rgba(0, 0, 0, 0.03); } .main { position: relative; z-index: 2; border-top: 1px solid #e6e6e6; } .toggle-all { width: 1px; height: 1px; border: none; /* Mobile Safari */ opacity: 0; position: absolute; right: 100%; bottom: 100%; } .toggle-all + label { width: 60px; height: 34px; font-size: 0; position: absolute; top: -52px; left: -13px; -webkit-transform: rotate(90deg); transform: rotate(90deg); } .toggle-all + label:before { content: "❯"; font-size: 22px; color: #e6e6e6; padding: 10px 27px 10px 27px; } .toggle-all:checked + label:before { color: #737373; } .todo-list { margin: 0; padding: 0; list-style: none; max-height: 420px; overflow: auto; } .todo-list li { position: relative; font-size: 24px; border-bottom: 1px solid #ededed; height: 60px; box-sizing: border-box; } .todo-list li:last-child { border-bottom: none; } .todo-list .view .index { position: absolute; color: gray; left: 10px; top: 20px; font-size: 16px; } .todo-list li .toggle { text-align: center; width: 40px; /* auto, since non-WebKit browsers doesn't support input styling */ height: auto; position: absolute; top: 0; bottom: 0; margin: auto 0; border: none; /* Mobile Safari */ -webkit-appearance: none; appearance: none; } .todo-list li .toggle { opacity: 0; } .todo-list li .toggle + label { /* Firefox requires `#` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433 IE and Edge requires *everything* to be escaped to render, so we do that instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/ */ background-image: url("data:image/svg+xml;utf8,"); background-repeat: no-repeat; background-position: center left; } .todo-list li .toggle:checked + label { background-image: url("data:image/svg+xml;utf8,"); } .todo-list li label { word-break: break-all; padding: 15px 15px 15px 60px; display: block; line-height: 1.2; transition: color 0.4s; } .todo-list li.completed label { color: #d9d9d9; text-decoration: line-through; } .todo-list li .destroy { display: none; position: absolute; top: 0; right: 10px; bottom: 0; width: 40px; height: 40px; margin: auto 0; font-size: 30px; color: #cc9a9a; margin-bottom: 11px; transition: color 0.2s ease-out; } .todo-list li .destroy:hover { color: #af5b5e; } .todo-list li .destroy:after { content: "×"; } .todo-list li:hover .destroy { display: block; } .todo-list li .edit { display: none; } .todo-list li.editing:last-child { margin-bottom: -1px; } .footer { color: #777; padding: 10px 15px; height: 20px; text-align: center; border-top: 1px solid #e6e6e6; } .footer:before { content: ""; position: absolute; right: 0; bottom: 0; left: 0; height: 50px; overflow: hidden; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), 0 8px 0 -3px #f6f6f6, 0 9px 1px -3px rgba(0, 0, 0, 0.2), 0 16px 0 -6px #f6f6f6, 0 17px 2px -6px rgba(0, 0, 0, 0.2); } .todo-count { float: left; text-align: left; } .todo-count strong { font-weight: 300; } .filters { margin: 0; padding: 0; list-style: none; position: absolute; right: 0; left: 0; } .filters li { display: inline; } .filters li a { color: inherit; margin: 3px; padding: 3px 7px; text-decoration: none; border: 1px solid transparent; border-radius: 3px; } .filters li a:hover { border-color: rgba(175, 47, 47, 0.1); } .filters li a.selected { border-color: rgba(175, 47, 47, 0.2); } .clear-completed, html .clear-completed:active { float: right; position: relative; line-height: 20px; text-decoration: none; cursor: pointer; } .clear-completed:hover { text-decoration: underline; } .info { margin: 50px auto 0; color: #bfbfbf; font-size: 15px; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); text-align: center; } .info p { line-height: 1; } .info a { color: inherit; text-decoration: none; font-weight: 400; } .info a:hover { text-decoration: underline; } /* Hack to remove background from Mobile Safari. Can't use it globally since it destroys checkboxes in Firefox */ @media screen and (-webkit-min-device-pixel-ratio: 0) { .toggle-all, .todo-list li .toggle { background: none; } .todo-list li .toggle { height: 40px; } } @media (max-width: 430px) { .footer { height: 50px; } .filters { bottom: 10px; } }
复制
----END----