這篇文章給大家分享的是有關vue中常用內置指令有哪些的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
vue常用內置指令
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>12_指令_內置指令</title> <style> [v-cloak] { display: none } </style> </head> <body> <!-- 常用內置指令 v:text : 更新元素的 textContent v-html : 更新元素的 innerHTML v-if : 如果為true, 當前標簽才會輸出到頁面 v-else: 如果為false, 當前標簽才會輸出到頁面 v-show : 通過控制display樣式來控制顯示/隱藏 v-for : 遍歷數組/對象 v-on : 綁定事件監聽, 一般簡寫為@ v-bind : 強制綁定解析表達式, 可以省略v-bind v-model : 雙向數據綁定 ref : 為某個元素注冊一個唯一標識, vue對象通過$refs屬性訪問這個元素對象 v-cloak : 使用它防止閃現表達式, 與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 href="http://www.baidu.com" 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"> <!-- 數據綁定 --> <a v-bind:href="url" rel="external nofollow" >百度一下</a> <!-- 雙向數據綁定 --> <input type="text" v-model="name"> <p>{{name}}</p> <!-- 綁定回車鍵 --> <input type="text" @keyup.enter="showEnt"> <!-- 點擊事件 --> <button @click="show('888')">按鈕</button> <!-- 獲取數組值 --> <p>{{arr[1]}}</p> <!-- 獲取對象屬性 --> <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>
計算屬性和監視
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>03_計算屬性和監視</title> </head> <body> <!-- 1. 計算屬性 在computed屬性對象中定義計算屬性的方法 在頁面中使用{{方法名}}來顯示計算的結果 2. 監視屬性: 通過通過vm對象的$watch()或watch配置來監視指定的屬性 當屬性變化時, 回調函數自動調用, 在函數內部進行計算 3. 計算屬性高級: 通過getter/setter實現對屬性數據的顯示和監視 計算屬性存在緩存, 多次讀取只執行一次getter計算 --> <div id="demo"> 姓: <input type="text" placeholder="First Name" v-model="firstName"><br> 名: <input type="text" placeholder="Last Name" v-model="lastName"><br> <!--fullName1是根據fistName和lastName計算產生--> 姓名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' }, // 計算屬性配置: 值為對象 computed: { fullName1:function() { // 屬性的get() return this.firstName + '-' + this.lastName; }, fullName3: { // 當獲取當前屬性值時自動調用, 將返回值(根據相關的其它屬性數據)作為屬性值 get () { return this.firstName + '-' + this.lastName }, // 當屬性值發生了改變時自動調用, 監視當前屬性值變化, 同步更新相關的其它屬性值 set (value) {// fullName3的最新value值 A-B23 // 更新firstName和lastName const names = value.split('-') this.firstName = names[0] this.lastName = names[1] } } }, watch: { // 配置監視firstName firstName: function (value) { // 相當于屬性的set // 更新fullName2 this.fullName2 = value + '-' + this.lastName } } }) // 監視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> <h4 v-for="user in users" v-bind:title="user.name"> {{user.name}} --- {{user.age}} </h4> <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. 理解 在應用界面中, 某個(些)元素的樣式是變化的 class/style綁定就是專門用來實現動態樣式效果的技術 2. class綁定: :class='xxx' xxx是字符串 xxx是對象 xxx是數組 3. style綁定 : 其中activeColor/fontSize是data屬性 --> <div id="demo"> <h3>1. class綁定: :class='xxx'</h3> <p :class="myClass">xxx是字符串</p> <p :class="{classA: hasClassA, classB: hasClassB}">xxx是對象</p> <p :class="['classA', 'classB']">xxx是數組</p> <h3>2. style綁定</h3> <p :>:</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. 綁定監聽: v-on:xxx="fun" @xxx="fun" @xxx="fun(參數)" 默認事件形參: event 隱含屬性對象: $event 2. 事件修飾符: .prevent : 阻止事件的默認行為 event.preventDefault() .stop : 停止事件冒泡 event.stopPropagation() 3. 按鍵修飾符 .keycode : 操作的是某個keycode值的健 .enter : 操作的是enter鍵 --> <div id="example"> <h3>1. 綁定監聽</h3> <button @click="test1">test1</button> <button @click="test2('abc')">test2</button> <button @click="test3('abcd', $event)">test3</button> <h3>2. 事件修飾符</h3> <!-- 阻止事件默認行為 --> <a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" @click.prevent="test4">百度一下</a> <div @click="test5"> <div @click.stop="test6"></div> <!-- 阻止事件冒泡 --> </div> <h3>3. 按鍵修飾符</h3> <!-- 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('點擊了鏈接') }, test5 () { alert('out') }, test6 () { alert('inner') }, test7 (event) { console.log(event.keyCode) alert(event.target.value) } } }) </script> </body> </html>
表單數據綁定
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>08_表單輸入綁定</title> </head> <body> <!-- 1. 使用v-model(雙向數據綁定)自動收集數據 text/textarea checkbox radio select --> <div id="demo"> <!-- 阻止表單自動提交,手動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>愛好: </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="注冊"> </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('提交注冊的ajax請求') } } }) </script> </body> </html>
生命周期
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>09_Vue實例_生命周期</title> </head> <body> <!-- 1. vue對象的生命周期 1). 初始化顯示 * beforeCreate() * created() * beforeMount() * mounted() 2). 更新狀態 * beforeUpdate() * updated() 3). 銷毀vue實例: vm.$destory() * beforeDestory() * destoryed() 2. 常用的生命周期方法 created()/mounted(): 發送ajax請求, 啟動定時器等異步任務 beforeDestory(): 做收尾工作, 如: 清除定時器 --> <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()') // 執行異步任務 this.intervalId = setInterval(() => { console.log('-----') this.isShow = !this.isShow }, 1000) }, beforeUpdate() { console.log('beforeUpdate()') }, updated () { console.log('updated()') }, beforeDestroy() { console.log('beforeDestroy()') // 執行收尾的工作 clearInterval(this.intervalId) }, destroyed() { console.log('destroyed()') }, methods: { destroyVue () { this.$destroy() } } }) </script> </body> </html>
過渡,動畫
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>10_過渡&動畫1</title> <style> /*指定過渡樣式*/ .xxx-enter-active, .xxx-leave-active { transition: opacity 1s } /*指定隱藏時的樣式*/ .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動畫的理解 操作css的trasition或animation vue會給目標元素添加/移除特定的class 2. 基本過渡動畫的編碼 1). 在目標元素外包裹<transition name="xxx"> 2). 定義class樣式 1>. 指定過渡樣式: transition 2>. 指定隱藏時的樣式: opacity/其它 3. 過渡的類名 xxx-enter-active: 指定顯示的transition xxx-leave-active: 指定隱藏的transition xxx-enter: 指定隱藏時的樣式 --> <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>
過濾器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>11_過濾器</title> </head> <body> <!-- 1. 理解過濾器 功能: 對要顯示的數據進行特定格式化后再顯示 注意: 并沒有改變原本的數據, 可是產生新的對應的數據 2. 編碼 1). 定義過濾器 Vue.filter(filterName, function(value[,arg1,arg2,...]){ // 進行一定的數據處理 return newValue }) 2). 使用過濾器 <div>{{myData | filterName}}</div> <div>{{myData | filterName(arg)}}</div> --> <!--需求: 對當前時間進行指定格式顯示--> <div id="test"> <h3>顯示格式化的日期時間</h3> <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> // 定義過濾器 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. 注冊全局指令 Vue.directive('my-directive', function(el, binding){ el.innerHTML = binding.value.toupperCase() }) 2. 注冊局部指令 directives : { 'my-directive' : { bind (el, binding) { el.innerHTML = binding.value.toupperCase() } } } 3. 使用指令 v-my-directive='xxx' --> <!-- 需求: 自定義2個指令 1. 功能類型于v-text, 但轉換為全大寫 2. 功能類型于v-text, 但轉換為全小寫 --> <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"> // 注冊一個全局指令 // el: 指令所在的標簽對象 // binding: 包含指令相關數據的容器對象 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" }, // 注冊局部指令 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是一款友好的、多用途且高性能的JavaScript框架,使用vue可以創建可維護性和可測試性更強的代碼庫,Vue允許可以將一個網頁分割成可復用的組件,每個組件都包含屬于自己的HTML、CSS、JavaScript,以用來渲染網頁中相應的地方,所以越來越多的前端開發者使用vue。
感謝各位的閱讀!關于“vue中常用內置指令有哪些”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。