vue常用指令代碼實(shí)例總結(jié)
更新時(shí)間:2020年03月16日 17:11:45 作者:爪白白
這篇文章主要介紹了vue常用指令代碼實(shí)例,需要的朋友可以參考下
vue常用內(nèi)置指令
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>12_指令_內(nèi)置指令</title> <style> [v-cloak] { display: none } </style> </head> <body> <!-- 常用內(nèi)置指令 v:text : 更新元素的 textContent v-html : 更新元素的 innerHTML v-if : 如果為true, 當(dāng)前標(biāo)簽才會(huì)輸出到頁(yè)面 v-else: 如果為false, 當(dāng)前標(biāo)簽才會(huì)輸出到頁(yè)面 v-show : 通過(guò)控制display樣式來(lái)控制顯示/隱藏 v-for : 遍歷數(shù)組/對(duì)象 v-on : 綁定事件監(jiān)聽(tīng), 一般簡(jiǎn)寫為@ v-bind : 強(qiáng)制綁定解析表達(dá)式, 可以省略v-bind v-model : 雙向數(shù)據(jù)綁定 ref : 為某個(gè)元素注冊(cè)一個(gè)唯一標(biāo)識(shí), vue對(duì)象通過(guò)$refs屬性訪問(wèn)這個(gè)元素對(duì)象 v-cloak : 使用它防止閃現(xiàn)表達(dá)式, 與css配合: [v-cloak] { display: none } --> <div id="example"> <p v-cloak>{{content}}</p> <p v-text="content"></p> <!--p.textContent = content--> <p v-html="content"></p> <!--p.innerHTML = content--> <p ref="msg">abcd</p> <button @click="hint">提示</button> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: '#example', data: { content: '<a rel="external nofollow" rel="external nofollow" >百度一下</a>' }, methods: { hint () { alert(this.$refs.msg.innerHTML) } } }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> </head> <body> <div id="app"> <!-- 數(shù)據(jù)綁定 --> <a v-bind:href="url" rel="external nofollow" >百度一下</a> <!-- 雙向數(shù)據(jù)綁定 --> <input type="text" v-model="name"> <p>{{name}}</p> <!-- 綁定回車鍵 --> <input type="text" @keyup.enter="showEnt"> <!-- 點(diǎn)擊事件 --> <button @click="show('888')">按鈕</button> <!-- 獲取數(shù)組值 --> <p>{{arr[1]}}</p> <!-- 獲取對(duì)象屬性 --> <p>{{users[1].name}}</p> </div> <script> var app = new Vue({ el: "#app", data: { name:'', url: 'http://www.baidu.com', arr: ["a", "b", "c", "d"], users: [ { name: "aowei", age: 12 }, { name: "baozi", age: 13 }, { name: "bbbbb", age: 14 }, ] }, methods: { // 綁定回車鍵 showEnt: function () { alert("666"); }, // 傳參 show: function (num) { alert(num); } }, } ) </script> </body> </html>
計(jì)算屬性和監(jiān)視
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>03_計(jì)算屬性和監(jiān)視</title> </head> <body> <!-- 1. 計(jì)算屬性 在computed屬性對(duì)象中定義計(jì)算屬性的方法 在頁(yè)面中使用{{方法名}}來(lái)顯示計(jì)算的結(jié)果 2. 監(jiān)視屬性: 通過(guò)通過(guò)vm對(duì)象的$watch()或watch配置來(lái)監(jiān)視指定的屬性 當(dāng)屬性變化時(shí), 回調(diào)函數(shù)自動(dòng)調(diào)用, 在函數(shù)內(nèi)部進(jìn)行計(jì)算 3. 計(jì)算屬性高級(jí): 通過(guò)getter/setter實(shí)現(xiàn)對(duì)屬性數(shù)據(jù)的顯示和監(jiān)視 計(jì)算屬性存在緩存, 多次讀取只執(zhí)行一次getter計(jì)算 --> <div id="demo"> 姓: <input type="text" placeholder="First Name" v-model="firstName"><br> 名: <input type="text" placeholder="Last Name" v-model="lastName"><br> <!--fullName1是根據(jù)fistName和lastName計(jì)算產(chǎn)生--> 姓名1(單向): <input type="text" placeholder="Full Name1" v-model="fullName1"><br> 姓名2(單向): <input type="text" placeholder="Full Name2" v-model="fullName2"><br> 姓名3(雙向): <input type="text" placeholder="Full Name3" v-model="fullName3"><br> <p>{{fullName1}}</p> <p>{{fullName1}}</p> </div> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> <script type="text/javascript"> const vm = new Vue({ el: '#demo', data: { firstName: 'A', lastName: 'B', fullName2: 'A-B' }, // 計(jì)算屬性配置: 值為對(duì)象 computed: { fullName1:function() { // 屬性的get() return this.firstName + '-' + this.lastName; }, fullName3: { // 當(dāng)獲取當(dāng)前屬性值時(shí)自動(dòng)調(diào)用, 將返回值(根據(jù)相關(guān)的其它屬性數(shù)據(jù))作為屬性值 get () { return this.firstName + '-' + this.lastName }, // 當(dāng)屬性值發(fā)生了改變時(shí)自動(dòng)調(diào)用, 監(jiān)視當(dāng)前屬性值變化, 同步更新相關(guān)的其它屬性值 set (value) {// fullName3的最新value值 A-B23 // 更新firstName和lastName const names = value.split('-') this.firstName = names[0] this.lastName = names[1] } } }, watch: { // 配置監(jiān)視firstName firstName: function (value) { // 相當(dāng)于屬性的set // 更新fullName2 this.fullName2 = value + '-' + this.lastName } } }) // 監(jiān)視lastName vm.$watch('lastName', function (value) { // 更新fullName2 this.fullName2 = this.firstName + '-' + value }) </script> </body> </html>
列表渲染
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <ul> <li v-for='item in arr'> {{item}} </li> </ul> <ul> <li v-for="(item,index) in arr"> {{index}} --- {{item}} </li> </ul> <h3 v-for="user in users" v-bind:title="user.name"> {{user.name}} --- {{user.age}} </h3> <button @click="add">add按鈕</button> <button @click="del">del按鈕</button> </div> <script> var app = new Vue({ el: "#app", data: { arr: ["a", "b", "c", "d"], users: [ { name: "aowei", age: 12 }, { name: "baozi", age: 13 }, { name: "bbbbb", age: 14 }, ] }, methods: { add: function () { console.log("add"); this.users.push({ name: "hello", age: "3" }); }, del: function () { console.log("del"); this.users.shift(); } }, } ) </script> </body> </html>
class & style 綁定
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>04_class與style綁定</title> <style> .classA { color: red; } .classB { background: blue; } .classC { font-size: 20px; } </style> </head> <body> <!-- 1. 理解 在應(yīng)用界面中, 某個(gè)(些)元素的樣式是變化的 class/style綁定就是專門用來(lái)實(shí)現(xiàn)動(dòng)態(tài)樣式效果的技術(shù) 2. class綁定: :class='xxx' xxx是字符串 xxx是對(duì)象 xxx是數(shù)組 3. style綁定 :style="{ color: activeColor, fontSize: fontSize + 'px' }" 其中activeColor/fontSize是data屬性 --> <div id="demo"> <h2>1. class綁定: :class='xxx'</h2> <p :class="myClass">xxx是字符串</p> <p :class="{classA: hasClassA, classB: hasClassB}">xxx是對(duì)象</p> <p :class="['classA', 'classB']">xxx是數(shù)組</p> <h2>2. style綁定</h2> <p :style="{color:activeColor, fontSize}">:style="{ color: activeColor, fontSize: fontSize + 'px' }"</p> <button @click="update">更新</button> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type="text/javascript"> new Vue({ el: '#demo', data: { myClass: 'classA', hasClassA: true, hasClassB: false, activeColor: 'red', fontSize: '20px' }, methods: { update () { this.myClass = 'classB' this.hasClassA = !this.hasClassA this.hasClassB = !this.hasClassB this.activeColor = 'yellow' this.fontSize = '30px' } } }) </script> </body> </html>
條件渲染
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>08_條件渲染</title> </head> <body> <!-- 1. 條件渲染指令 v-if v-else v-show 2. 比較v-if與v-show 如果需要頻繁切換 v-show 較好 --> <div id="demo"> <p v-if="ok">表白成功</p> <p v-else>表白失敗</p> <hr> <p v-show="ok">求婚成功</p> <p v-show="!ok">求婚失敗</p> <button @click="ok=!ok">切換</button> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: '#demo', data: { ok: true, } }) </script> </body> </html>
事件處理
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>07_事件處理</title> </head> <body> <!-- 1. 綁定監(jiān)聽(tīng): v-on:xxx="fun" @xxx="fun" @xxx="fun(參數(shù))" 默認(rèn)事件形參: event 隱含屬性對(duì)象: $event 2. 事件修飾符: .prevent : 阻止事件的默認(rèn)行為 event.preventDefault() .stop : 停止事件冒泡 event.stopPropagation() 3. 按鍵修飾符 .keycode : 操作的是某個(gè)keycode值的健 .enter : 操作的是enter鍵 --> <div id="example"> <h2>1. 綁定監(jiān)聽(tīng)</h2> <button @click="test1">test1</button> <button @click="test2('abc')">test2</button> <button @click="test3('abcd', $event)">test3</button> <h2>2. 事件修飾符</h2> <!-- 阻止事件默認(rèn)行為 --> <a rel="external nofollow" rel="external nofollow" @click.prevent="test4">百度一下</a> <div style="width: 200px;height: 200px;background: red" @click="test5"> <div style="width: 100px;height: 100px;background: blue" @click.stop="test6"></div> <!-- 阻止事件冒泡 --> </div> <h2>3. 按鍵修飾符</h2> <!-- enter鍵/13 --> <input type="text" @keyup.13="test7"> <input type="text" @keyup.enter="test7"> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: '#example', data: { }, methods: { test1(event) { alert(event.target.innerHTML) }, test2 (msg) { alert(msg) }, test3 (msg, event) { alert(msg+'---'+event.target.textContent) }, test4 () { alert('點(diǎn)擊了鏈接') }, test5 () { alert('out') }, test6 () { alert('inner') }, test7 (event) { console.log(event.keyCode) alert(event.target.value) } } }) </script> </body> </html>
表單數(shù)據(jù)綁定
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>08_表單輸入綁定</title> </head> <body> <!-- 1. 使用v-model(雙向數(shù)據(jù)綁定)自動(dòng)收集數(shù)據(jù) text/textarea checkbox radio select --> <div id="demo"> <!-- 阻止表單自動(dòng)提交,手動(dòng)ajax提交 --> <form action="/xxx" @submit.prevent="handleSubmit"> <span>用戶名: </span> <input type="text" v-model="username"><br> <span>密碼: </span> <input type="password" v-model="pwd"><br> <span>性別: </span> <input type="radio" id="female" value="女" v-model="sex"> <label for="female">女</label> <input type="radio" id="male" value="男" v-model="sex"> <label for="male">男</label><br> <span>愛(ài)好: </span> <input type="checkbox" id="basket" value="basket" v-model="likes"> <label for="basket">籃球</label> <input type="checkbox" id="foot" value="foot" v-model="likes"> <label for="foot">足球</label> <input type="checkbox" id="pingpang" value="pingpang" v-model="likes"> <label for="pingpang">乒乓</label><br> <span>城市: </span> <select v-model="cityId"> <option value="">未選擇</option> <option :value="city.id" v-for="(city, index) in allCitys" :key="city.id">{{city.name}}</option> </select><br> <span>介紹: </span> <textarea rows="10" v-model="info"></textarea><br><br> <input type="submit" value="注冊(cè)"> </form> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: '#demo', data: { username: '', pwd: '', sex: '男', likes: ['foot'], allCitys: [{id: 1, name: 'BJ'}, {id: 2, name: 'SS'}, {id: 3, name: 'SZ'}], cityId: '2', info: '' }, methods: { handleSubmit () { console.log(this.username, this.pwd, this.sex, this.likes, this.cityId, this.info) alert('提交注冊(cè)的ajax請(qǐng)求') } } }) </script> </body> </html>
生命周期
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>09_Vue實(shí)例_生命周期</title> </head> <body> <!-- 1. vue對(duì)象的生命周期 1). 初始化顯示 * beforeCreate() * created() * beforeMount() * mounted() 2). 更新?tīng)顟B(tài) * beforeUpdate() * updated() 3). 銷毀vue實(shí)例: vm.$destory() * beforeDestory() * destoryed() 2. 常用的生命周期方法 created()/mounted(): 發(fā)送ajax請(qǐng)求, 啟動(dòng)定時(shí)器等異步任務(wù) beforeDestory(): 做收尾工作, 如: 清除定時(shí)器 --> <div id="test"> <button @click="destroyVue">destory vue</button> <p v-if="isShow">尚硅谷IT教育</p> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: '#test', data: { isShow: true }, beforeCreate() { console.log('beforeCreate()') }, created() { console.log('created()') }, beforeMount() { console.log('beforeMount()') }, mounted () { console.log('mounted()') // 執(zhí)行異步任務(wù) this.intervalId = setInterval(() => { console.log('-----') this.isShow = !this.isShow }, 1000) }, beforeUpdate() { console.log('beforeUpdate()') }, updated () { console.log('updated()') }, beforeDestroy() { console.log('beforeDestroy()') // 執(zhí)行收尾的工作 clearInterval(this.intervalId) }, destroyed() { console.log('destroyed()') }, methods: { destroyVue () { this.$destroy() } } }) </script> </body> </html>
過(guò)渡,動(dòng)畫
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>10_過(guò)渡&動(dòng)畫1</title> <style> /*指定過(guò)渡樣式*/ .xxx-enter-active, .xxx-leave-active { transition: opacity 1s } /*指定隱藏時(shí)的樣式*/ .xxx-enter, .xxx-leave-to { opacity: 0; } .move-enter-active { transition: all 1s } .move-leave-active { transition: all 3s } .move-enter, .move-leave-to { opacity: 0; transform: translateX(20px) } </style> </head> <body> <!-- 1. vue動(dòng)畫的理解 操作css的trasition或animation vue會(huì)給目標(biāo)元素添加/移除特定的class 2. 基本過(guò)渡動(dòng)畫的編碼 1). 在目標(biāo)元素外包裹<transition name="xxx"> 2). 定義class樣式 1>. 指定過(guò)渡樣式: transition 2>. 指定隱藏時(shí)的樣式: opacity/其它 3. 過(guò)渡的類名 xxx-enter-active: 指定顯示的transition xxx-leave-active: 指定隱藏的transition xxx-enter: 指定隱藏時(shí)的樣式 --> <div id="demo"> <button @click="show = !show">Toggle</button> <transition name="xxx"> <p v-show="show">hello</p> </transition> </div> <hr> <div id="demo2"> <button @click="show = !show">Toggle2</button> <transition name="move"> <p v-show="show">hello</p> </transition> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: '#demo', data: { show: true } }) new Vue({ el: '#demo2', data: { show: true } }) </script> </body> </html>
過(guò)濾器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>11_過(guò)濾器</title> </head> <body> <!-- 1. 理解過(guò)濾器 功能: 對(duì)要顯示的數(shù)據(jù)進(jìn)行特定格式化后再顯示 注意: 并沒(méi)有改變?cè)镜臄?shù)據(jù), 可是產(chǎn)生新的對(duì)應(yīng)的數(shù)據(jù) 2. 編碼 1). 定義過(guò)濾器 Vue.filter(filterName, function(value[,arg1,arg2,...]){ // 進(jìn)行一定的數(shù)據(jù)處理 return newValue }) 2). 使用過(guò)濾器 <div>{{myData | filterName}}</div> <div>{{myData | filterName(arg)}}</div> --> <!--需求: 對(duì)當(dāng)前時(shí)間進(jìn)行指定格式顯示--> <div id="test"> <h2>顯示格式化的日期時(shí)間</h2> <p>{{time}}</p> <p>最完整的: {{time | dateString}}</p> <p>年月日: {{time | dateString('YYYY-MM-DD')}}</p> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript" src="https://cdn.bootcss.com/moment.js/2.22.1/moment.js"></script> <script> // 定義過(guò)濾器 Vue.filter('dateString', function (value, format='YYYY-MM-DD HH:mm:ss') { return moment(value).format(format); }) new Vue({ el: '#test', data: { time: new Date() }, mounted () { setInterval(() => { this.time = new Date() }, 1000) } }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>12_指令_自定義指令</title> </head> <body> <!-- 1. 注冊(cè)全局指令 Vue.directive('my-directive', function(el, binding){ el.innerHTML = binding.value.toupperCase() }) 2. 注冊(cè)局部指令 directives : { 'my-directive' : { bind (el, binding) { el.innerHTML = binding.value.toupperCase() } } } 3. 使用指令 v-my-directive='xxx' --> <!-- 需求: 自定義2個(gè)指令 1. 功能類型于v-text, 但轉(zhuǎn)換為全大寫 2. 功能類型于v-text, 但轉(zhuǎn)換為全小寫 --> <div id="test"> <p v-upper-text="msg"></p> <p v-lower-text="msg"></p> </div> <div id="test2"> <p v-upper-text="msg"></p> <p v-lower-text="msg"></p> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> // 注冊(cè)一個(gè)全局指令 // el: 指令所在的標(biāo)簽對(duì)象 // binding: 包含指令相關(guān)數(shù)據(jù)的容器對(duì)象 Vue.directive('upper-text', function (el, binding) { console.log(el, binding) el.textContent = binding.value.toUpperCase() }) new Vue({ el: '#test', data: { msg: "I Like You" }, // 注冊(cè)局部指令 directives: { 'lower-text'(el, binding) { console.log(el, binding) el.textContent = binding.value.toLowerCase() } } }) new Vue({ el: '#test2', data: { msg: "I Like You Too" } }) </script> </body> </html>
本文主要介紹了vue常用指令代碼實(shí)例,更多關(guān)于vue常用指令請(qǐng)查看下面的相關(guān)鏈接
您可能感興趣的文章:
- Vue 通過(guò)自定義指令回顧v-內(nèi)置指令(小結(jié))
- vue內(nèi)置指令詳解
- vue動(dòng)態(tài)渲染svg、添加點(diǎn)擊事件的實(shí)現(xiàn)
- Vue事件處理原理及過(guò)程詳解
- vue全屏事件開(kāi)發(fā)詳解
- vue中的雙向數(shù)據(jù)綁定原理與常見(jiàn)操作技巧詳解
- 原生javascript實(shí)現(xiàn)類似vue的數(shù)據(jù)綁定功能示例【觀察者模式】
- Vue的雙向數(shù)據(jù)綁定實(shí)現(xiàn)原理解析
- Vue表單控件數(shù)據(jù)綁定方法詳解
- 淺談vue中關(guān)于checkbox數(shù)據(jù)綁定v-model指令的個(gè)人理解
- vue-router之實(shí)現(xiàn)導(dǎo)航切換過(guò)渡動(dòng)畫效果
- vue實(shí)現(xiàn)鼠標(biāo)經(jīng)過(guò)動(dòng)畫
- Vue仿微信app頁(yè)面跳轉(zhuǎn)動(dòng)畫效果
- vue2 v-model/v-text 中使用過(guò)濾器的方法示例
- vue中過(guò)濾器filter的講解
- 如何去除富文本中的html標(biāo)簽及vue、react、微信小程序中的過(guò)濾器
相關(guān)文章
Python Django view 兩種return的實(shí)現(xiàn)方式
這篇文章主要介紹了Python Django view 兩種return的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03OpenCV中resize函數(shù)插值算法的實(shí)現(xiàn)過(guò)程(五種)
最新版OpenCV2.4.7中,cv::resize函數(shù)有五種插值算法:最近鄰、雙線性、雙三次、基于像素區(qū)域關(guān)系、蘭索斯插值。感興趣的可以了解一下2021-06-06Python基于ThreadingTCPServer創(chuàng)建多線程代理的方法示例
這篇文章主要介紹了Python基于ThreadingTCPServer創(chuàng)建多線程代理的方法,結(jié)合實(shí)例形式分析了Python使用ThreadingTCPServer模塊實(shí)現(xiàn)多線程代理功能進(jìn)行網(wǎng)絡(luò)請(qǐng)求響應(yīng)的相關(guān)操作技巧,需要的朋友可以參考下2018-01-01python實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)的方法
這篇文章主要介紹了python實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)的方法,涉及Python中os模塊及codecs模塊的相關(guān)使用技巧,需要的朋友可以參考下2015-05-05