其他分享
首页 > 其他分享> > 前端演示购物车案例、生命预期钩子函数、与后端交互演示

前端演示购物车案例、生命预期钩子函数、与后端交互演示

作者:互联网

今日内容概要

内容详细

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>

image

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>

image

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>

image

2、生命周期钩子函数

# new Vue这个对象---》管理一个标签---》把数据,渲染到页面上

# 组件---》对象管理某一个html片段

# 生命周期--》8个声明周期钩子函数---》执行到某个地方,就会执行某个函数


# 主要记忆:
	created:向后端发请求拿数据,发送ajax请求
	mounted:定时任务,延迟任务  js中
	beforeDestroy:定时任务关闭,销毁一些操作

image

代码演示:

<!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>

image

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>

image

image

案例:电影展示

# 电影数据自行创建文件导入

# 后端代码:
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>

image

标签:el,console,name,钩子,购物车,checkGroup,演示,data,log
来源: https://www.cnblogs.com/jgx0/p/16142744.html