Vue 核心基礎(2.X)
小編:管理員 169閱讀 2022.08.18

官網:
- 英文官網: https://vuejs.org/
- 中文官網: https://cn.vuejs.org/
- 遵循MVVM模式
- 編碼簡潔,體積小,運行效率高,適合移動/ PC 端開發
- 它本身只關注 UI, 可以輕松的引入 vue 插件或其他的第三庫開發項目
永遠的 HelloWord
編碼:
<div id="app"> <input type="text" v-model="username" /> <p>Hello, {{username}}</p> </div> <script src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ // 配置對象: 屬性名是一些特定的名稱 el: "#app", // 值是選擇器 element 用來查找跟元素 data: { username: "OY_test", // 包含多個可變數據的對象,相當于state,為模板頁面提供數據 }, }); </script>復制
效果示例:

Vue 的 MVVM

模板的理解
- 動態的 html 頁面
-
包含了一些 JS 語法代碼
- 雙大括號表達式 ({{}}`) - 指令(以 v-開頭的自定義標簽屬性) ### 1、雙大括號表達式 - **語法:** `{{exp}}
- 功能: 向頁面輸出數據
- 可以調用對象的方法
- 語法 指定變化的屬性值
- 完整寫法:v-bin:xxx = ‘yyy’ (yyy 會作為表達式解析執行)
- 簡介寫法: :xxx = ‘yyy’
- 功能:綁定指定事件名的回調函數
- 完整寫法:
v-on:keyup='xxx' v-on:keyup='xxx'(參數) v-on:keyup.enter='xxx'復制
- 簡介寫法:
@keyup='xxx' @keyup.enter='xxx'復制4、編碼示例
<div id="app"> <h2>1. 雙大括號表達式</h2> <p>{{msg}}</p> <p>{{msg.toUpperCase()}}</p> <h2>2. 指令一: 強制數據綁定</h2> <a href="url">訪問指定站點</a><br/><!--不能使用--> <a v-bind:href="url">訪問指定站點2</a><br/> <a :href="url">訪問指定站點3</a> <h2>3. 指令二: 綁定事件監聽</h2> <button v-on:click="handleClick">點我</button> <button @click="handleClick">點我2</button> </div> <script src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: "#app", data: { msg: "NBA I Like This Game!", url: "http://www.baidu.com", }, methods: { handleClick() { alert("處理點擊"); }, }, }); </script>復制
效果示例:

- 在 computed 屬性對象中定義計算屬性的方法
- 在頁面中使用{{方法名}}來顯示計算的結果
- 通過 vm 對象的 $watch() 或 watch 配置來監視指定的屬性
- 當屬性變化時,回調函數自動調用,在函數內部進行計算
<div id="demo"> 姓: <input type="text" placeholder="First Name" v-model="firstName"><br> 名: <input type="text" placeholder="Last Name" v-model="lastName"><br> 姓名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> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> var vm = new Vue({ el: "#demo", data: { firstName: "Kobe", lastName: "bryant", fullName2: "Kobe bryant", }, computed: { fullName1: function () { return this.firstName + " " + this.lastName; }, fullName3: { get: function () { return this.firstName + " " + this.lastName; }, set: function (value) { var names = value.split(" "); this.firstName = names[0]; this.lastName = names[1]; }, }, }, watch: { lastName: function (newVal, oldVal) { this.fullName2 = this.firstName + " " + newVal; }, }, }); vm.$watch("fistName", function (val) { this.fullName2 = val + " " + this.lastName; }); </script>復制
效果示例:

- :class = ‘xxx’
- 表達式是字符串: ‘classA’
- 表達式是對象:{classA: isA, classB: isB}
- 表達式是數組:[‘classA’,’classB’]
- :style=”{color: activeColor, fontSize: fontSize + ‘px’}”
- 其中 activeColor/fontSize 是 data 屬性
<div id="demo"> <h2>1. class綁定: :class='xxx'</h2> <p class="classC" :class="Myclass">xxxx</p> <p :class="{classA: hasA, classB: hasB}">yyyy</p> <p :class="['classA','classB']">zzz</p> <h2>2. style綁定</h2> <p :style="{color: Mycolor, fontSize: mySize + 'px'}">xxxxxxx</p> <button @click="update">更新</button> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: "#demo", data: { Myclass: "classA", hasA: true, hasB: false, Mycolor: "red", mySize: 20, }, methods: { update() { console.log(this); (this.Myclass = "classB"), (this.hasA = !this.hasA), (this.hasB = !this.hasB), (this.Mycolor = "#ff0000"), (this.mySize = 30); }, }, }); </script>復制
效果示例:

- v-if 與 v-else
- v-show
- 如果需要頻繁切換 v-show 較好
- 當條件不成立時,v-if 的所有子節點不會解析(項目中使用)
<div id="demo"> <p v-if="ok">表白成功</p> <p v-else>表白失敗</p> <p v-show="ok">求婚成功</p> <p v-show="!ok">求婚失敗</p> <button @Click="toggle">切換</button> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: "#demo", data() { return { ok: true, }; }, methods: { toggle() { this.ok = !this.ok; }, }, }); </script>復制
效果示例:

- 數組: v-for / index
- 對象: v-for / key
- 刪除 Item
- 替換 Item
列表過濾
-
VUE 數據綁定如何實現?
- Vue 會監視 data 中所有的層次的屬性
- 對象中的屬性數據通過添加 set 方法來實現監視
-
數組中的元素對應也實現了監視;重寫數組一系列更新元素的方法
- 調用原生的對應的方法對元素進行處理
- 去更新界面
<div id="demo"> <h2>測試: v-for 遍歷數組</h2> <ul> <li v-for="(p, index) in persons" :key="p.id"> {{p.id}} -- {{p.name}} -- {{p.age}} -- <button @click="deleteP(index)">刪除</button> -- <button @click="updateP(index,{id: Date.now(), name: 'Jarry',age: 19})">更新</button> </li> </ul> <h2>測試: v-for 遍歷對象</h2> <ul> <li v-for="(value, key) in persons[0]" :key="key"> {{key}} = {{value}} </li> </ul> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: "#demo", data: { persons: [ { id: 1, name: "Tom", age: 15 }, { id: 2, name: "Jack", age: 12 }, { id: 4, name: "Bob", age: 17 }, { id: 6, name: "Rose", age: 16 }, { id: 8, name: "Else", age: 13 }, ], }, methods: { deleteP(index) { this.persons.splice(index, 1); }, updateP(index, newP) { // 第一種方式 // this.persons[index].id = newP.id; // this.Persons[index].name = newP.name; // this.Persons[index].age = newP.age; // this.persons[index] = newP // 不會更新界面 this.persons.splice(index, 1, newP); // VUE重寫后的splice方法 }, }, }); </script>復制
效果示例:

列表排序
<div id="app"> <input type="text" v-model="searchName"> <ul> <li v-for="(p, index) in filterPersons" :key="p.id"> {{p.id}} -- {{p.name}} -- {{p.age}} </li> </ul> <button @click="sortType=2">按年齡升序</button> <button @click="sortType=3">按年齡降序</button> <button @click="sortType=1">原本順序</button> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: "#app", data: { searchName: "", sortType: 1, // 排序的類型, 1:不排序, 2:升序, 3: 降序 persons: [ { id: 1, name: "Tom", age: 15 }, { id: 2, name: "Jack", age: 12 }, { id: 4, name: "Bob", age: 17 }, { id: 6, name: "Rose", age: 16 }, { id: 8, name: "Else", age: 13 }, ], }, computed: { filterPersons() { // 1.得到依賴數據 const { sortType, searchName, persons } = this; // 2. 進行計算處理,產生結果數據并返回 // 過濾 const arr = persons.filter((p) => p.name.indexOf(searchName) >= 0); // 進行排序 if (sortType !== 1) { arr.sort((p1, p2) => { if (sortType === 2) { // 升序 return p1.age - p2.age; } else { // 降序 return p2.age - p1.age; } }); } return arr; }, }, }); </script>復制
效果示例:

- v-on:xxx=”fun”
- @xxx=”fun”
- @xxx=”fun(參數)”
- 默認事件形參: event
- 隱含屬性對象: $event
- .prevent: 阻止事件的默認行為 event.preventDefault()
- .stop: 停止對事件冒泡 event.stopPropagation()
- .keycode: 操作的是某個 keycode 值的鍵
- .keyName: 操作的某個按鍵名的鍵(少部分)

<div id="example"> <h2>1. 綁定監聽</h2> <button @click="test1">test1</button> <button @click="test2('abc')">test2</button> <button @click="test3('abc',$event)">test3</button> <h2>2. 事件修飾符</h2> <!-- 阻止(prevent)事件的默認行為 停止(stop)事件冒泡 --> <a @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> <p @clik.once="test6">xxxxx</p> <h2>3. 按鍵修飾符</h2> <input type="text" v-model="msg" @Keyup.13="test7"> <input type="text" v-model="msg" @Keyup.enter="test7"> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: '#example', data: { msg: '' }, methods: { test1(e){ alert(e.target.innerText); }, test2(value){ alert(value); }, test3(value,event){ alert(value+"---" + event.target.innerText); }, test4(event){ //event.preventDefault(); alert('點擊了'); }, test5(){ alert('out'); }, test6(){ alert('inner'); }, test7(){ alert(this.msg) } } }) </script>復制
效果示例:

- text/textarea
- checkbox
- radio
- select
<div id="demo"> <form action="/xxx" @submit.prevent="register"> <span>用戶名: </span> <input type="text" v-model="user.username"><br> <span>密碼: </span> <input type="password" v-model="user.pwd"><br> <span>性別: </span> <input type="radio" id="female" v-model="user.sex" value="女"> <label for="female">女</label> <input type="radio" id="male" v-model="user.sex" value="男"> <label for="male">男</label><br> <span>愛好: </span> <input type="checkbox" id="basket" v-model="user.likes" value="basket"> <label for="basket">籃球</label> <input type="checkbox" id="foot" v-model="user.likes" value="foot"> <label for="foot">足球</label> <input type="checkbox" id="pingpang" v-model="user.likes" value="pingpang"> <label for="pingpang">乒乓</label><br> <span>城市: </span> <select v-model="user.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="user.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: { user: { username: "", pwd: "", sex: "女", likes: ["foot"], cityID: "1", info: "", }, allcitys: [ { id: 1, name: "HN" }, { id: 2, name: "SZ" }, { id: 3, name: "HB" }, ], }, methods: { register() { alert("發送注冊的ajax請求:" + JSON.stringify(this.user)); }, }, }); </script>復制
示例效果:


- 初始化顯示
- beforeCreate()
- created()
- beforeMount()
- mounted()
- 更新狀態: this.xxx = value
- beforeUpdate()
- updated()
- 銷毀 vue 實例:vm.$destory()
- beforeDestory()
- destoryed()
- created()/mounted() : 發送 ajax 請求,啟動定時器等異步任務。
- beforeDestory(): 做收尾工作, 如: 清除定時器。
<div id="test"> <button @click="destoryVM">destory vue</button> <p v-show="isShow" ref="content">Vue 生命周期 {{isShow ? 'show...' : 'hide...'}}</p> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: "#test", data() { return { isShow: true, }; }, beforeCreate() { console.log("beforeCreate()", this.isShow); }, // 實現數據代碼: 后面可以通過vm 讀取data 中的數據 created() { console.log("created()"); }, // 在第一次顯示之后在顯示 mounted() { console.log("mounted()"); this.intervalId = setInterval(() => { console.log("-----"); this.isShow = !this.isShow; }, 1000); }, beforeUpdate() { // 讀取是老的界面 console.log("beforeUpdate()", this.isShow, this.$refs.content.innerHTML); }, updated() { console.log("updated()", this.isShow, this.$refs.content.innerHTML); }, // 銷毀之前執行一次 beforeDestroy() { console.log("beforeDestroy()"); clearInterval(this.intervalId); }, destroyed() { console.log("destroyed()"); }, methods: { destoryVM() { this.$destroy(); }, }, }); </script>復制
實例效果:


- 操作 css 的 trasition 或 animation
- vue 會給目標元素添加/移除特定的 class
-
過渡的相關類名
- xxx-enter-active: 指定顯示的 transition
- xxx-leave-active: 指定隱藏的 transition
- xxx-enter/xxx-leave-to: 指定隱藏時的樣式

- 在目標元素外包裹 <transition name=”xxx”>
-
定義 class 樣式
- 指定過渡樣式:transition
- 指定隱藏時的樣式: opacity/其他
示例一:
<style type="text/css"> /*過渡樣式*/ .move-enter-active, .move-leave-active { transition: opacity 5s; } /*隱藏時的樣式*/ .move-enter, .move-leave-to { opacity: 0; } /*顯示的過渡樣式*/ .move2-enter-active { transition: all 1s; } /*隱藏的過渡樣式*/ .move2-leave-active { transition: all 5s; } /*隱藏時的樣式*/ .move2-enter, .move2-leave-to { opacity: 0; transform: translateX(20px); } </style> <div id="demo"> <button v-on:click="show=!show"> Toggle </button> <transition name="move"> <p v-show="show">Hello</p> </transition> </div> <div id="demo2"> <button v-on:click="show=!show"> Toggle2 </button> <transition name="move2"> <p v-show="show">Hello2</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>復制
效果示例:

示例二:
<style> /*顯示動畫樣式*/ .bounce-enter-active { animation: bounce-in 0.5s; } .bounce-leave-active { animation: bounce-in 0.5s reverse; } @keyframes bounce-in { 0% { transform: scale(0); } 50% { transform: scale(1.5); } 100% { transform: scale(1); } } </style> <div id="example-2"> <button @click="show = !show">Toggle show</button><br> <transition name="bounce"> <p v-if="show" style="display: inline-block;">Lorem</p> </transition> </div> <script type="text/javascript" src="../js/vue.js"></script> <script> new Vue({ el: "#example-2", data: { show: true, }, }); </script>復制
效果示例:

1、定義和使用過濾器功能: 對要顯示的數據進行特定格式化在顯示 注意:并沒有改變原有的數據,是產生新的對應的數據
- 定義過濾器
Vue.filter(filterName,function(value[arg1,arg2,...])){ // 進行一定的數據處理 return newValue; }復制
- 使用過濾器
<div>{{myData | filterName}}</div> <div>{{myData | filterName(arg)}}</div>復制2、編碼示例
<div id="test"> <h2>顯示格式化的日期時間</h2> <p>{{startTime}}</p> <p>{{startTime | dateFormate}}</p> <p>{{startTime | dateFormate('YYYY-MM-DD')}}</p> <p>{{startTime | dateFormate('HH:mm:ss')}}</p> </div> <script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.1/moment.js"></script> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> // 自定義過濾器 Vue.filter("dateFormate", function (value, formatStr = "YYYY-MM-DD HH:mm:ss") { //return moment(value).format(formatStr || 'YYYY-MM-DD HH:mm:ss') return moment(value).format(formatStr); }); new Vue({ el: "#test", data() { return { startTime: Date.now() - 10000, }; }, }); </script>復制
效果示例:

指令 |
描述 |
---|---|
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 對象通過$els 屬性訪問這個元素對象 |
v-cloak |
防止閃現, 與 css 配合: [v-cloak] { display: none } |
- 注冊全局指令
Vue.directive('my-directive', function(el, binding){ el.innerHTML = binding.value.toupperCase() })復制
- 注冊局部指令
directives : { 'my-directive' : { bind (el, binding) { el.innerHTML = binding.value.toupperCase() } } }復制
- 使用指令
v-my-directive = 'xxx'復制3、編碼示例
內置指令
<div id="example"> <p v-text="msg"></p> <p v-html="msg"></p> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: "#example", data() { return { msg: '<a , }; }, }); </script>復制
效果示例:

自定義指令
<!-- 需求: 自定義2個指令 1. 功能類型于v-text, 但轉換為全大寫 2. 功能類型于v-text, 但轉換為全小寫 --> <div id="test"> <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"> // 自定義全局指令 Vue.directive("upper-text", (el, binding) => { console.log("upper-text", binding); el.innerText = binding.value.toUpperCase(); }); new Vue({ el: "#test", data: { msg: "I will Back!", }, // 定義局部指令(只對當前vm的模板有效) directives: { "lower-text"(el, binding) { el.innerText = binding.value.toLowerCase(); }, }, }); </script>復制
效果示例:

說明:
- Vue 插件是一個包含 install 方法的對象
- 通過 install 方法給 Vue 或 Vue 實例添加方法,定義全局指令
編碼示例:
- 插件 JS (vue-myPlugin.js)
/* 自定義插件 */ (function () { const MyPlugin = {}; MyPlugin.install = function (Vue, options) { // 1.添加全局方法或屬性 Vue.myGlobalMethod = function () { alert("Vue 函數對象方法執行"); }; // 2.添加全局資源 Vue.directive("my-directive", function (el, binding) { el.innerHTML = "MyPlugin my-directive " + binding.value; }); // 3.添加實例方法 Vue.prototype.$myMethod = function () { alert("vue 實例對象方法執行"); }; }; window.MyPlugin = MyPlugin; })();復制
- 頁面使用插件
<div id="demo"> <!-- 使用自定義指令 --> <p v-my-directive="msg"></p> </div> <script type="text/javascript" src="../js/vue.js"></script> <script src="vue-myPlugin.js"></script> <script type="text/javascript"> // 使用自定義插件 Vue.use(MyPlugin); var vm = new Vue({ el: "#demo", data: { msg: "OY_Test", }, }); // 調用自定義的靜態方法 Vue.myGlobalMethod(); // 調用自定義的對象方法 vm.$myMethod(); </script>復制
效果示例:

相關推薦
- Vue3(二)工程化開發方式做項目 工程化的開發方式這是開發中、大型項目的必備技能,網上資料也很多,這里只是一個簡單的綜合性的介紹。包括vue的全家桶、建立項目的幾種方式、UI庫的簡單使用等?梢院蜕弦黄腸nd方式做項目做一下對比。node.js,npm、cnpm、yarnnode.js執行 npm run serve ,…
- Hibernate Criterion 在查詢方法設計上能夠靈活的依據Criteria的特點來方便地進行查詢條件的組裝.Hibernate設計了CriteriaSpecification作為Criteria的父接口,以下提供了Criteria和DetachedCriteria.Criteria和DetachedCriteria的主要差別在于創建的形式不一樣,Criteria是在線的,所…