Vue生命周期與后端交互實(shí)現(xiàn)流程詳解
表單控制
1.input:checkbox(單選,多選),radio(單選)
2.代碼展示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="app"> <h1>表單控制</h1> <p>用戶名:<input type="text" v-model="name"></p> <p>密碼:<input type="text" v-model="password"></p> <p><input type="checkbox" v-model="isRemember">記住密碼</p> <p> <input type="radio" v-model="gender" value="1">男 <input type="radio" v-model="gender" value="2">女 <input type="radio" v-model="gender" value="0">未知 </p> <p> 愛好: <input type="checkbox" value="籃球" v-model="hobby">籃球 <input type="checkbox" value="足球" v-model="hobby">足球 <input type="checkbox" value="乒乓球" v-model="hobby">乒乓球 <input type="checkbox" value="排球" v-model="hobby">排球 </p> {{hobby}} </div> </body> <script> new Vue({ el:'#app', data:{ name:'', password:'', isRemember:false, //checkbox單選,使用布爾類型 gender:'', //radio單選,使用字符串 hobby:[] //checkbox多選使用數(shù)組 } }) </script> </html>
購物車案例
1.python中只有基于迭代的循環(huán)可沒有基于索引的循環(huán)
2.js,java,go基于迭代和索引的兩種
3.js中for循環(huán)
- for(i=0;i<checkGroup.length;i++) # 基于索引的循環(huán)
- for(i in checkGroup) # 基于迭代的循環(huán)
- for(i of checkGroup) # es6中的循環(huán)
- 數(shù)組內(nèi)置方法.forEach()
- jquery $.each循環(huán)
代碼展示:
1 方式一:js的基于索引的循環(huán) for (var i = 0; i< goodList.length; i++) { console.log(goodList[i]) } 2 方式二:基于迭代的循環(huán) for (i in goodList){ console.log(goodList[i]) } 3 方式三:of 循環(huán),基于迭代的 for (i of goodList){ console.log(i) } 4 方式四:數(shù)組的循環(huán)方法 goodList.forEach(item => { console.log('---', item) }) 5 jquery:引入 $.each(goodList, (i, v) => { console.log(v) })
4.基本購物車代碼展示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script> <link rel="stylesheet" > rel="external nofollow" rel="external nofollow" > </head> <body> <div id="app"> <div class="container-fluid"> <h1 class="text-center">購物車</h1> <div class="row"> <div class="col-md-6 col-md-offset-3"> <table class="table table-bordered"> <thead> <tr> <th>商品id</th> <th>商品名字</th> <th>商品價格</th> <th>商品數(shù)量</th> </tr> </thead> <tbody> <tr v-for="good in goodList"> <th>{{good.id}}</th> <td>{{good.name}}</td> <td>{{good.price}}</td> <td>{{good.count}}</td> <td><input type="checkbox" v-model="checkGroup" :value="good"></td> </tr> </tbody> </table> <hr> 選中的商品是:{{checkGroup}} <br> 總價格是:{{getPrice()}} </div> </div> </div> </div> </body> <script> new Vue({ el: '#app', data: { goodList: [ {id: 1, name: '小汽車', price: 1200000, count: 1}, {id: 2, name: '鋼筆', price: 12, count: 34}, {id: 3, name: '雞蛋', price: 2, count: 4}, {id: 4, name: '面包', price: 9, count: 10}, ], checkGroup: [] }, methods: { getPrice() { // 取出checkGroup中得商品數(shù)量和商品價格相乘 做累加 // js 中 for 循環(huán) var total = 0 for (item of this.checkGroup) { total += item.price * item.count } return total } } }) var goodList = [ {id: 1, name: '小汽車', price: 1200000, count: 1}, {id: 2, name: '鋼筆', price: 12, count: 34}, {id: 3, name: '雞蛋', price: 2, count: 4}, {id: 4, name: '面包', price: 9, count: 10}, ] </script> </html>
5.帶加減的購物車代碼展示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> <link rel="stylesheet" rel="external nofollow" rel="external nofollow" > </head> <body> <div id="app"> <div class="container-fluid"> <h1 class="text-center">購物車</h1> <div class="row"> <div class="col-md-6 col-md-offset-3"> <table class="table table-bordered"> <thead> <tr> <th>商品id</th> <th>商品名字</th> <th>商品價格</th> <th>商品數(shù)量</th> <th><input type="checkbox" v-model="checkAll" @change="handleChange">全選/全不選</th> </tr> </thead> <tbody> <tr v-for="good in goodList"> <th>{{good.id}}</th> <td>{{good.name}}</td> <td>{{good.price}}</td> <td><span class="btn link btn-sm" @click="handleDown(good)">-</span>{{good.count}}<span class="btn link btn-sm" @click="good.count++">+</span> </td> <td><input type="checkbox" v-model="checkGroup" :value="good" @change="handleCheckOne"></td> </tr> </tbody> </table> <hr> 選中的商品是:{{checkGroup}} <br> 總價格是:{{getPrice()}} </div> </div> </div> </div> </body> <script> new Vue({ el: '#app', data: { goodList: [ {id: 1, name: '小汽車', price: 1200000, count: 1}, {id: 2, name: '鋼筆', price: 12, count: 34}, {id: 3, name: '雞蛋', price: 2, count: 4}, {id: 4, name: '面包', price: 9, count: 10}, ], checkGroup: [], checkAll: false, }, methods: { getPrice() { var total = 0 for (item of this.checkGroup) { total += item.price * item.count } return total }, handleChange() { if (this.checkAll) { this.checkGroup = this.goodList } else { this.checkGroup = [] } }, handleCheckOne() { // 如果checkGroup的長度等于goodList的長度,說明全選了,checkAll就應(yīng)該變?yōu)閠rue,否則就是false // if (this.checkGroup.length == this.goodList.length) { // this.checkAll = true // } else { // this.checkAll = false // } // 變短 this.checkAll = this.checkGroup.length == this.goodList.length }, handleDown(good) { if (good.count > 1) { good.count-- } else { alert('不能再少了,受不了了') } } } }) </script> </html>
v-model進(jìn)階(了解)
1.v-model 之 lazy、number、trim
- lazy:等待input框的數(shù)據(jù)綁定時區(qū)焦點(diǎn)之后在變化;
- number:數(shù)字開頭,只保留數(shù)字,后面的字母不保留;字母開頭都保留。
- trim:取出首位的空格。
2.代碼展示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> </head> <body> <div id="app"> <h1>v-model進(jìn)階</h1> <input type="text" v-model.lazy ="name1">----->{{name1}} <br> <input type="text" v-model.number ="name2">----->{{name2}} <br> <input type="text" v-model.trim ="name3">----->{{name3}} </div> </body> <script> var vm = new Vue({ el: '#app', data: { name1: '', name2:'', name3:'', }, }) </script> </html>
vue生命周期
1.var vm=new Vue實(shí)例()
四個過程:
- 實(shí)例創(chuàng)建,數(shù)據(jù)放到實(shí)例中;
- 掛在模板:el====》div;
- 改頁面,改變量,都會相互影響,update;
- 銷毀實(shí)例
2.八個鉤子函數(shù)
4個過程對應(yīng)八個函數(shù),依次執(zhí)行(到某個過程就會執(zhí)行某個函數(shù))
beforeCreate 創(chuàng)建Vue實(shí)例之前調(diào)用,data,el都沒有
created 創(chuàng)建Vue實(shí)例成功后調(diào)用(可以在此處發(fā)送異步請求后端數(shù)據(jù)),data有了,el沒有的
beforeMount 渲染DOM之前調(diào)用 ,data有了,el沒有
mounted 渲染DOM之后調(diào)用
beforeUpdate 重新渲染之前調(diào)用(數(shù)據(jù)更新等操作時,控制DOM重新渲染)
updated 重新渲染完成之后調(diào)用
beforeDestroy 銷毀之前調(diào)用
destroyed 銷毀之后調(diào)用
鉤子函數(shù)(hook),AOP的體現(xiàn):面向切面編程----》裝飾器實(shí)現(xiàn)aop;
3.學(xué)習(xí)生命周期需要掌握
- 組件想后端發(fā)送請求,獲取數(shù)據(jù),應(yīng)該放在created寫,此時data已經(jīng)有數(shù)據(jù);
- destroyed做一些資源請理性的工作。
4.小案例:
組件創(chuàng)建,開啟定時器,不停的打印hello,在destroyed中對定時器進(jìn)行銷毀。 補(bǔ)充之js定時任務(wù)和延時任務(wù): 延時任務(wù):
setTimeout(()=>{ console.log('3s后執(zhí)行我') },3000)
定時任務(wù):
setInterval(()=>{ console.log('hello') },3000)
什么場景下要用定時任務(wù)?
(1)實(shí)時跟后端交互,基于http+定時任務(wù)(websocket協(xié)議:服務(wù)端主動推送消息,手機(jī)app的消息推送)
(2)秒殺場景,先提交秒殺請求,每隔3s,查詢是否秒到;
代碼展示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> </head> <body> <div id="app"> <h1>vue聲明周期</h1> <button @click="handleShow">點(diǎn)我組件顯示和消失</button> <hr> <child v-if="show"></child> <hr> </div> </body> <script> // 定義一個全局組件 Vue.component('child', { template: ` <div> <button>后退</button> {{ title }} <button @click="handleClick">前進(jìn)</button> </div>`, data() { return { title: '好看的首頁', t:'' } }, methods: { handleClick() { // alert('前進(jìn)') this.title = 'lqz' } }, beforeCreate() { console.log('beforeCreate') console.log(this.$data) console.log(this.$el) }, created() { console.log('created') console.log(this.$data) console.log(this.$el) // 開啟定時器,每隔3s,打印hello this.t=setInterval(()=>{ console.log('hello') },3000) }, beforeMount() { console.log('beforeMount') console.log(this.$data) console.log(this.$el) }, mounted() { console.log('mounted') console.log(this.$data) console.log(this.$el) }, beforeUpdate() { console.log('beforeUpdate') }, updated() { console.log('updated') }, beforeDestroy() { console.log('當(dāng)前狀態(tài):beforeDestroy') }, destroyed() { console.log('當(dāng)前狀態(tài):destroyed') // 銷毀定時器 clearInterval(this.t) this.t=null }, }) var vm = new Vue({ el: '#app', data: { show: true }, methods: { handleShow() { this.show = !this.show } } }) </script> </html>
與后端交互
1.發(fā)展過程
- js原生發(fā)送ajax請求:new XMLHttpRequest(),瀏覽器兼容性不好,于是jquery基于它做了封裝出了jquery的ajax方法,XMLHttpRequest中存在很多bug;
- jquery的ajax,vue中用的很少;
- js原生提供的fetch,現(xiàn)在官方主推這個,缺點(diǎn)是不執(zhí)行ie瀏覽器;
- axios:vue中常用的,它是封裝了XMLHttpRequest
2.代碼展示
前端頁面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> </head> <body> <div id="app"> <h1>jquery的ajax與后端交互</h1> <!-- <button @click="handleLoad1">點(diǎn)擊加載數(shù)據(jù)</button>--> <!-- <br>--> <!-- <p>名字是:{{name}}</p>--> <!-- <p>年齡是:{{age}}</p>--> <!-- <hr>--> <h1>js原生的fetch與后端交互</h1> <!-- <button @click="handleLoad2">點(diǎn)擊加載數(shù)據(jù)</button>--> <!-- <br>--> <!-- <p>名字是:{{name}}</p>--> <!-- <p>年齡是:{{age}}</p>--> <!-- <hr>--> <h1>axios與后端交互</h1> <button @click="handleLoad3">點(diǎn)擊加載數(shù)據(jù)</button> <br> <p>名字是:{{name}}</p> <p>年齡是:{{age}}</p> <hr> </div> </body> <script> var vm = new Vue({ el: '#app', data: { name: '', age: 0 }, methods: { handleLoad1() { $.ajax({ url: "http://127.0.0.1:5000/", type: 'get', success: data => { console.log(typeof data) data = JSON.parse(data) // data 是字符串類型,需要轉(zhuǎn)成對象類型 console.log(typeof data) this.name = data.name this.age = data.age } }) }, handleLoad2() { // 用的很少 fetch('http://127.0.0.1:5000/').then(res => res.json()).then(res => { console.log(res) console.log(typeof res) this.name = res.name this.age = res.age }) }, handleLoad3() { // 用的很少 axios.get('http://127.0.0.1:5000/').then(res => { console.log(res.data) // 后端真正的數(shù)據(jù)在res.data中 this.name = res.data.name this.age = res.data.age }) }, } }) </script> </html>
后端Flask框架:
from flask import Flask, jsonify app = Flask(__name__) @app.route('/') def index(): res = jsonify({'name': 'lqz', 'age': 19}) # 處理了跨域() 在響應(yīng)頭中加入 django寫后端 {'Access-Control-Allow-Origin': '*'} res.headers = {'Access-Control-Allow-Origin': '*'} return res if __name__ == '__main__': app.run()
電影案例
前端頁面展示:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"> <h1>電影小案例</h1> <ul> <li v-for="film in filmList"> <h2>電影名:{{film.name}}</h2> <img :src="film.poster" alt="" height="400px" width="300px"> </li> </ul> </div> </body> <script> var vm = new Vue({ el: '#app', data: { filmList: [] }, created() { axios.get('http://127.0.0.1:5000/films').then(res => { this.filmList = res.data.data.films }) } }) </script> </html>
后盾Flask框架:
from flask import Flask, jsonify app = Flask(__name__) @app.route('/films') def films(): with open('./film.json', 'r', encoding='utf-8') as f: data = json.load(f) res = jsonify(data) res.headers = {'Access-Control-Allow-Origin': '*'} return res if __name__ == '__main__': app.run()
到此這篇關(guān)于Vue生命周期與后端交互實(shí)現(xiàn)流程詳解的文章就介紹到這了,更多相關(guān)Vue生命周期與后端交互內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3?函數(shù)式彈窗的實(shí)例小結(jié)
這篇文章主要介紹了Vue3?函數(shù)式彈窗的實(shí)例小結(jié),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-11-11Vue Element前端應(yīng)用開發(fā)之界面語言國際化
我們開發(fā)的系統(tǒng),一般可以不用考慮語言國際化的問題,大多數(shù)系統(tǒng)一般是給本國人使用的,而且直接使用中文開發(fā)界面會更加迅速 一些,不過框架最好能夠支持國際化的處理,以便在需要的時候,可以花點(diǎn)時間來實(shí)現(xiàn)多語言切換的處理,使系統(tǒng)具有更廣泛的受眾用戶。2021-05-05vue如何在style標(biāo)簽中使用變量(數(shù)據(jù))詳解
在我們編寫css樣式中是不能直接使用vue data中的變量的,下面這篇文章主要給大家介紹了關(guān)于vue如何在style標(biāo)簽中使用變量(數(shù)據(jù))的相關(guān)資料,需要的朋友可以參考下2022-09-09