前端演示購物車案例、生命預期鉤子函式、與後端互動演示
阿新 • • 發佈:2022-04-14
今日內容概要
- 購物車案例
- 生命週期鉤子函式
- 與後端互動
內容詳細
1、購物車案例
1.1 基本購物車
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div id="app"> <div class="container-fluid"> <div class="row"> <div class="col-md-offset-3 col-md-6" style="margin-top: 20px"> <h1>購物車案例</h1> <table class="table table-bordered"> <tr> <td>商品名字</td> <td>價格</td> <td>數量</td> </tr> <tr v-for="data in dataList"> <td>{{data.name}}</td> <td>{{data.price}}</td> <td>{{data.number}}</td> <td><input type="checkbox" v-model="checkGroup" :value="data"></td> </tr> </table> <br> 選中的商品:{{checkGroup}} <br> 總價格:{{getPrice()}} </div> </div> </div> </div> </body> <script> var vm = new Vue({ el: '#app', data: { dataList: [ {name: '今瓶沒', price: 99, number: 2}, {name: '西柚記', price: 59, number: 1}, {name: '水壺轉', price: 89, number: 5}, ], checkGroup: [], }, methods: { getPrice() { var total = 0 // 自動計算所選商品總價 // 方式一: i是索引,迴圈選中的商品,基於迭代的迴圈 // for (i in this.checkGroup) { // total += this.checkGroup[i].price * this.checkGroup[i].number // } // 方式二: 基於索引的迴圈 // for (var i=0;i<this.checkGroup.length;i++) { // total += this.checkGroup[i].price * this.checkGroup[i].number // } // 方式三: 基於迭代 for of // for (v of this.checkGroup) { // total += v.price * v.number // } // 方式四:forEach 可迭代物件(陣列)的方法 this.checkGroup.forEach((v, i) => { total += v.price * v.number }) return total } } }) </script> </html>
1.2 購物車全選全不選功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div id="app"> <div class="container-fluid"> <div class="row"> <div class="col-md-offset-3 col-md-6" style="margin-top: 20px"> <h1>購物車案例</h1> <table class="table table-bordered"> <tr> <td>商品名字</td> <td>價格</td> <td>數量</td> <td>全選/全不選 <input type="checkbox" v-model="allCheck" @change="handleAll"></td> </tr> <tr v-for="data in dataList"> <td>{{data.name}}</td> <td>{{data.price}}</td> <td>{{data.number}}</td> <td><input type="checkbox" v-model="checkGroup" :value="data" @change="checkOne"></td> </tr> </table> <br> 選中的商品:{{checkGroup}} <br> 總價格:{{getPrice()}} <br> 是否全選:{{allCheck}} </div> </div> </div> </div> </body> <script> var vm = new Vue({ el: '#app', data: { dataList: [ {name: '今瓶沒', price: 99, number: 2}, {name: '西柚記', price: 59, number: 1}, {name: '水壺轉', price: 89, number: 5}, ], checkGroup: [], allCheck: false }, methods: { getPrice() { var total = 0 // 自動計算所選商品總價 // 方式四:forEach 可迭代物件(陣列)的方法 this.checkGroup.forEach((v, i) => { total += v.price * v.number }) return total }, handleAll() { if (this.allCheck) { this.checkGroup = this.dataList } else { this.checkGroup = [] } }, checkOne() { // if(this.checkGroup.length==this.dataList.length){ // this.allCheck=true // }else { // this.allCheck=false // } // js中 == 和 === 區別:==比較的是值,===值和型別 // 等同於上面 this.allCheck = (this.checkGroup.length === this.dataList.length) } } }) </script> </html>
1.3 數量增減
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div id="app"> <div class="container-fluid"> <div class="row"> <div class="col-md-offset-3 col-md-6" style="margin-top: 20px"> <h1>購物車案例</h1> <table class="table table-bordered"> <tr> <td>商品名字</td> <td>價格</td> <td>數量</td> <td>全選/全不選 <input type="checkbox" v-model="allCheck" @change="handleAll"></td> </tr> <tr v-for="data in dataList"> <td>{{data.name}}</td> <td>{{data.price}}</td> <td> <button @click="handleCount(data)">-</button> {{data.number}} <button @click="data.number++">+</button> </td> <td><input type="checkbox" v-model="checkGroup" :value="data" @change="checkOne"></td> </tr> </table> <br> 選中的商品:{{checkGroup}} <br> 總價格:{{getPrice()}} <br> 是否全選:{{allCheck}} </div> </div> </div> </div> </body> <script> var vm = new Vue({ el: '#app', data: { dataList: [ {name: '今瓶沒', price: 99, number: 2}, {name: '西柚記', price: 59, number: 1}, {name: '水壺轉', price: 89, number: 5}, ], checkGroup: [], allCheck: false }, methods: { getPrice() { var total = 0 // 自動計算所選商品總價 // 方式四:forEach 可迭代物件(陣列)的方法 this.checkGroup.forEach((v, i) => { total += v.price * v.number }) return total }, handleAll() { if (this.allCheck) { this.checkGroup = this.dataList } else { this.checkGroup = [] } }, checkOne() { // if(this.checkGroup.length==this.dataList.length){ // this.allCheck=true // }else { // this.allCheck=false // } // js中 == 和 === 區別:==比較的是值,===值和型別 // 等同於上面 this.allCheck = (this.checkGroup.length === this.dataList.length) } } }) </script> </html>
2、生命週期鉤子函式
# new Vue這個物件---》管理一個標籤---》把資料,渲染到頁面上
# 元件---》物件管理某一個html片段
# 生命週期--》8個宣告週期鉤子函式---》執行到某個地方,就會執行某個函式
# 主要記憶:
created:向後端發請求拿資料,傳送ajax請求
mounted:定時任務,延遲任務 js中
beforeDestroy:定時任務關閉,銷燬一些操作
程式碼演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="./js/vue.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="app">
<button @click="handleC">點我顯示元件</button>
<child v-if="is_show"></child>
<hr>
</div>
</body>
<script>
// 1 定義個元件---》生命週期
Vue.component('child', {
template: `
<div>
<h1>{{ name }}</h1>
<button @click="handleC">點我彈窗</button>
</div>`,
data() {
return {
name: "lqz",
t: '',
}
},
methods: {
handleC() {
this.name = "彭于晏"
alert(this.name)
}
},
// 生命週期鉤子函式8個
beforeCreate() {
console.log('當前狀態:beforeCreate')
console.log('當前el狀態:', this.$el)
console.log('當前data狀態:', this.$data)
console.log('當前name狀態:', this.name)
},
created() {
// 向後端載入資料
console.log('當前狀態:created')
console.log('當前el狀態:', this.$el)
console.log('當前data狀態:', this.$data)
console.log('當前name狀態:', this.name)
},
beforeMount() {
console.log('當前狀態:beforeMount')
console.log('當前el狀態:', this.$el)
console.log('當前data狀態:', this.$data)
console.log('當前name狀態:', this.name)
},
mounted() {
console.log('當前狀態:mounted')
console.log('當前el狀態:', this.$el)
console.log('當前data狀態:', this.$data)
console.log('當前name狀 態:', this.name)
// 用的最多,向後端載入資料,建立定時器等
// setTimeout:延遲執行
// setInterval:定時執行,每三秒鐘列印一下daada
this.t = setInterval(() => {
console.log('daada')
}, 3000)
},
beforeUpdate() {
console.log('當前狀態:beforeUpdate')
console.log('當前el狀態:', this.$el)
console.log('當前data狀態:', this.$data)
console.log('當前name狀態:', this.name)
},
updated() {
console.log('當前狀態:updated')
console.log('當前el狀態:', this.$el)
console.log('當前data狀態:', this.$data)
console.log('當前name狀態:', this.name)
},
beforeDestroy() {
console.log('當前狀態:beforeDestroy')
console.log('當前el狀態:', this.$el)
console.log('當前data狀態:', this.$data)
console.log('當前name狀態:', this.name)
},
destroyed() {
console.log('當前狀態:destroyed')
console.log('當前el狀態:', this.$el)
console.log('當前data狀態:', this.$data)
console.log('當前name狀態:', this.name)
//元件銷燬,清理定時器
clearInterval(this.t)
this.t = null
// console.log('destoryed')
},
})
var vm = new Vue({
el: '#app',
data: {
is_show: false
},
methods: {
handleC() {
this.is_show = !this.is_show
}
},
})
</script>
</html>
3、與後端互動
# ajax:
非同步的xml請求,前後端互動就是xml格式,隨著json格式發展,目前都是使用json格式
# jquery的ajax方法
$.ajax() 方法---》只是方法名正好叫ajax
# js原生可以寫ajax請求,非常麻煩,考慮相容性---》jquery
# 方式一:
jquery的ajax方法傳送請求(基本不用了)
# 方式二:
js官方提供的fetch方法(XMLHttpRequest)(官方的,用的也少)
# 方式三:
axios第三方,做ajax請求(用的最多的)
程式碼演示:
# 後端程式碼:
from flask import Flask, make_response, jsonify
app = Flask(__name__)
@app.route('/')
def index():
# 跨域問題
obj = make_response(jsonify({'name': 'lqz is handsome', 'age': 19}))
obj.headers['Access-Control-Allow-Origin'] = '*'
return obj
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">{{text}}</div>
</body>
<script>
var vm = new Vue({
el: '#app',
data: {
text: '',
},
created() {
// 方式一:向後端發請求,拿資料,拿回來賦值給text
// $.ajax({
// url: 'http://127.0.0.1:5000/',
// type: 'get',
// success: (data) => {
// console.log(data)
// this.text = data
// }
// })
// 方式二:js原生的fetch
// fetch('http://127.0.0.1:5000/').then(res => res.json()).then(res => {
// console.log(res)
// this.text = res.name
// })
// 方式三 axios
axios.get('http://127.0.0.1:5000').then(data => {
console.log(data.data)
this.text = data.data.name
})
}
})
</script>
</html>
案例:電影展示
# 電影資料自行建立檔案匯入
# 後端程式碼:
from flask import Flask, make_response, jsonify
app = Flask(__name__)
@app.route('/')
def index():
# 跨域問題
obj = make_response(jsonify({'name': 'lqz is handsome', 'age': 19}))
obj.headers['Access-Control-Allow-Origin'] = '*'
return obj
@app.route('/films')
def films():
# 跨域問題
import json
with open('./res.json', 'r', encoding='utf-8') as f:
res = json.load(f)
obj = make_response(jsonify(res))
obj.headers['Access-Control-Allow-Origin'] = '*'
return obj
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">
<ul>
<li v-for="film in films_list">
<p>電影名字是:{{film.name}}</p>
<img :src="film.poster" alt="" width="100px" height="150px">
<p>電影介紹:{{film.synopsis}}</p>
</li>
</ul>
</div>
</body>
<script>
var vm = new Vue({
el: '#app',
data: {
films_list: []
},
created() {
// 方式三 axios
axios.get('http://127.0.0.1:5000/films').then(res => {
console.log(res.data)
this.films_list = res.data.data.films
})
}
})
</script>
</html>