本文實(shí)例講述了vue.js綁定事件監(jiān)聽器。分享給大家供大家參考,具體如下:
<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>www.survivalescaperooms.com 綁定事件監(jiān)聽器</title> <!-- Vue.js --> <script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script></head><body><div id="app"> <p v-if="show">這是一段文本</p> <buttton v-on:click="handleClose">點(diǎn)擊隱藏</buttton></div></body></html><script> //當(dāng)數(shù)據(jù)show的值為true時(shí),p元素會被插入,為false時(shí)會被移除 var myData = { show:true }; var app = new Vue({ el:'#app', data:myData, //在普通元素上,v-on可以監(jiān)聽原生的DOM事件,除了click外,還有dbclick、keyup、mousemove等。表達(dá)式可以是一個(gè)方法名,這些方法都寫在vue實(shí)例的methods屬性內(nèi),并且是函數(shù)的形式,函數(shù)內(nèi)的this指向的是當(dāng)前vue實(shí)例本身,因此可以直接使用this.xxx的形式來訪問或者修改數(shù)據(jù),如實(shí)例中的this.show = false;把數(shù)據(jù)show修改為了false,所以點(diǎn)擊按鈕時(shí),文本p元素就被移除了 methods:{ handleClose:function () {// this.show = false //在handleClose方法內(nèi),直接通過close()調(diào)用了close函數(shù)。在示例中是多此一舉的,只是用于演示它的用法 this.close() }, close:function () { this.show = false } } })</script>使用本站HTML/CSS/JS在線運(yùn)行測試工具:http://tools.VeVB.COm/code/HtmlJsRun,可得到如下測試運(yùn)行效果:

再來看一個(gè)例子:
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title>vue</title> <script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script> </head> <body> <div id="test">{{msg}} <p v-for="val in arr"> {{val.a}} </p> <a href="javascript:void(0)" rel="external nofollow" v-on:click="tap">點(diǎn)我</a> </div> </body></html><script> // window.onload= function(){ var app2 = new Vue ({ el:"#test", data:{ msg:'潤元裝飾', msg1:"家裝"+new Date(), msg2:'lianxi', show:true, arr:[ {a:'bb'}, {a:'cc'} ] }, methods:{ tap : function(){ this.arr.unshift({a:'new'}) } } }) // }</script>該示例可響應(yīng)鼠標(biāo)點(diǎn)擊自動增加元素,感興趣的朋友可以使用HTML/CSS/JS在線運(yùn)行測試工具:http://tools.VeVB.COm/code/HtmlJsRun測試一下效果。
希望本文所述對大家vue.js程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答