其他分享
首页 > 其他分享> > 事件处理之按键修饰符,表单控制之checkbox单选多选和radio,基本购物车,带多选,单选购物车,数量加减购物车,v-model进阶,vue生命周期,vue与后端交互

事件处理之按键修饰符,表单控制之checkbox单选多选和radio,基本购物车,带多选,单选购物车,数量加减购物车,v-model进阶,vue生命周期,vue与后端交互

作者:互联网

1 事件处理之按键修饰符

# 键盘有很多键,   回车,esc....  按下或者抬起能够触发某个事件(函数执行)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>VUE</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.0.0/jquery.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
</head>
<body>
<div id="app">
    <h1>事件处理之按键修饰符</h1>
    <p>普通使用: <input type="text" v-model="myText" @keydown="KeyDown($event)"></p>
    <br>
    <p>监控enter键:input <input type="text" v-model="myText" @keydown.enter="KeyDown1"></p>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#app',
        data: {
            myText: '',
        },
        methods: {
            KeyDown(event) {
                console.log(event)
            },
            KeyDown1() {
                swal('回车了', '', 'success')
            },
        },
    })
</script>
</html>

2 表单控制之checkbox单选多选和radio

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.0.0/jquery.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
</head>
<body>
<div id="app">
    <h1>checkbox单选---使用布尔值</h1>
    <p><input type="text" placeholder="请输入用户名" v-model="username"></p>
    <p><input type="text" placeholder="请输入密码" v-model="password"></p>
    <p><input type="checkbox" v-model="checkBox" value="1">记住密码</p>
    <br>
    {{checkBox}}

    <br>
    <h1>checkbox多选---使用数组</h1>
    <input type="checkbox" v-model="check_many" value="1">喝酒
    <input type="checkbox" v-model="check_many" value="2">烫头
    <input type="checkbox" v-model="check_many" value="3">抽烟
    <input type="checkbox" v-model="check_many" value="4">睡觉
    <br>
    {{check_many}}


    <h1>radio---使用字符串</h1>
    <input type="text" placeholder="请输入用户名" v-model="username">
    <input type="text" placeholder="请输入密码" v-model="password">
    <br>
    性别:
    <input type="radio" v-model="gender" value="1">男
    <input type="radio" v-model="gender" value="2">女
    <input type="radio" v-model="gender" value="0">未知
    <br>
    {{gender}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#app',
        data: {
            username: '',
            password: '',
            checkBox: false,
            check_many: [],
            gender: '',
        },
        methods: {},
    })
</script>
</html>

3 基本购物车

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.0.0/jquery.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
</head>
<body>
<div id="app">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h1>基本购物车</h1>
            <table class="table table-striped">
                <thead>
                <tr>
                    <th>商品名</th>
                    <th>商品价格</th>
                    <th>商品数量</th>
                    <th>选则</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for=" item in data_list">
                    <th>{{item.name}}</th>
                    <td>{{item.price}}</td>
                    <td>{{item.number}}</td>
                    <td><input type="checkbox" v-model="checkGroup" :value="item"></td>
                </tr>
                </tbody>
            </table>
            <br>
            总价格是:{{sumMoney()}}
            <br>
            选中了:{{checkGroup}}
        </div>
    </div>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#app',
        data: {
            data_list: [
                {name: '金梅', price: 99, number: 2},
                {name: '钢板', price: 59, number: 1},
                {name: '水壶转', price: 89, number: 5},
                {name: '特斯拉', price: 230000, number: 3}
            ],
            checkGroup: [],
        },
        methods: {
            sumMoney() {
                var total = 0
                // 循环方式一
                // for (i = 0; i < this.checkGroup.length; i++) {
                //     total += this.checkGroup[i].price * this.checkGroup[i].number
                // }

                // 循环方式二  对象,数组的方法
                // this.checkGroup.forEach(function (value,index){
                //     total+=value.price*value.number
                // })


                // 循环方式三
                // for (i in this.checkGroup){  // i 是索引
                //     total += this.checkGroup[i].price * this.checkGroup[i].number
                // }

                // 循环方式四
                for (item of this.checkGroup) {  // item 是索引
                    total += item.price * item.number
                }
                return total
            },
        },
    })
</script>
</html>

4 带多选,单选购物车

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.0.0/jquery.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
</head>
<body>
<div id="app">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h1>基本购物车</h1>
            <table class="table table-striped">
                <thead>
                <tr>
                    <th>商品名</th>
                    <th>商品价格</th>
                    <th>商品数量</th>
                    <th>全选/全部选<input type="checkbox" v-model="checkAll" @change="checkAll1"></th>
                </tr>
                </thead>
                <tbody>
                <tr v-for=" item in data_list">
                    <th>{{item.name}}</th>
                    <td>{{item.price}}</td>
                    <td>
                        <button @click="item.number++">+</button>
                        {{item.number}}
                        <button @click="reduceNum(item)">-</button>
                    </td>
                    <td><input type="checkbox" @change="checkone" v-model="checkGroup" :value="item"></td>
                </tr>
                </tbody>
            </table>
            <br>
            总价格是:{{sumMoney()}}
            <br>
            选中了:{{checkGroup}}
        </div>
    </div>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#app',
        data: {
            data_list: [
                {name: '金梅', price: 99, number: 2},
                {name: '钢板', price: 59, number: 1},
                {name: '水壶转', price: 89, number: 5},
                {name: '特斯拉', price: 230000, number: 3}
            ],
            checkGroup: [],
            checkAll: false,
        },
        methods: {
            sumMoney() {
                var total = 0
                // 循环方式一
                // for (i = 0; i < this.checkGroup.length; i++) {
                //     total += this.checkGroup[i].price * this.checkGroup[i].number
                // }

                // 循环方式二  对象,数组的方法
                // this.checkGroup.forEach(function (value,index){
                //     total+=value.price*value.number
                // })


                // 循环方式三
                // for (i in this.checkGroup){  // i 是索引
                //     total += this.checkGroup[i].price * this.checkGroup[i].number
                // }

                // 循环方式四
                for (item of this.checkGroup) {  // item 是索引
                    total += item.price * item.number
                }
                return total
            },

            checkAll1() {
                if (this.checkAll) {
                    this.checkGroup = this.data_list
                } else {
                    this.checkGroup = []
                }
            },
            checkone() {
                this.checkAll = this.checkGroup.length == this.data_list.length
            },
            reduceNum(item) {
                if (item.number < 1) {
                    swal('不能再少了,手下留情吧', '', 'error')
                } else {
                    item.number--
                }
            },
        },
    })
</script>
</html>

5 数量加减购物车

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.0.0/jquery.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
</head>
<body>
<div id="app">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h1>基本购物车</h1>
            <table class="table table-striped">
                <thead>
                <tr>
                    <th>商品名</th>
                    <th>商品价格</th>
                    <th>商品数量</th>
                    <th>全选/全部选<input type="checkbox" v-model="checkAll" @change="checkAll1"></th>
                </tr>
                </thead>
                <tbody>
                <tr v-for=" item in data_list">
                    <th>{{item.name}}</th>
                    <td>{{item.price}}</td>
                    <td>
                        <button @click="item.number++">+</button>
                        {{item.number}}
                        <button @click="reduceNum(item)">-</button>
                    </td>
                    <td><input type="checkbox" @change="checkone" v-model="checkGroup" :value="item"></td>
                </tr>
                </tbody>
            </table>
            <br>
            总价格是:{{sumMoney()}}
            <br>
            选中了:{{checkGroup}}
        </div>
    </div>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#app',
        data: {
            data_list: [
                {name: '金梅', price: 99, number: 2},
                {name: '钢板', price: 59, number: 1},
                {name: '水壶转', price: 89, number: 5},
                {name: '特斯拉', price: 230000, number: 3}
            ],
            checkGroup: [],
            checkAll: false,
        },
        methods: {
            sumMoney() {
                var total = 0
                // 循环方式一
                // for (i = 0; i < this.checkGroup.length; i++) {
                //     total += this.checkGroup[i].price * this.checkGroup[i].number
                // }

                // 循环方式二  对象,数组的方法
                // this.checkGroup.forEach(function (value,index){
                //     total+=value.price*value.number
                // })


                // 循环方式三
                // for (i in this.checkGroup){  // i 是索引
                //     total += this.checkGroup[i].price * this.checkGroup[i].number
                // }

                // 循环方式四
                for (item of this.checkGroup) {  // item 是索引
                    total += item.price * item.number
                }
                return total
            },

            checkAll1() {
                if (this.checkAll) {
                    this.checkGroup = this.data_list
                } else {
                    this.checkGroup = []
                }
            },
            checkone() {
                this.checkAll = this.checkGroup.length == this.data_list.length
            },
            reduceNum(item) {
                if (item.number < 1) {
                    swal('不能再少了,手下留情吧', '', 'error')
                } else {
                    item.number--
                }
            },
        },
    })
</script>
</html>

6 v-model进阶

# lazy:等待input框的数据绑定失去焦点之后再变化
# number:数字开头,只保留数字,后面的字母不保留;字母开头,都保留
# trim:去除首位的空格
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>
</head>
<body>
<div id="app">
    lazy的使用:<input type="text" v-model.lazy="myText">--->{{myText}}
    <hr>
    number的使用:<input type="text" v-model.number="myText2">--->{{myText2}}
    <hr>
     trim的使用:<input type="text" v-model.trim="myText3">--->{{myText3}}




</div>
</body>
<script>
    new Vue({
        el: '#app',
        data: {
            myText: '',
            myText2: '',
            myText3: '',
        },
    })


</script>
</html>

7 vue生命周期

# 组件化开发---》页面也是一个组件---》一个组件就是一个Vue的对象----》Vue对象是有生命周期---》从创建那一刻到销毁的过程叫生命周期

# 生命周期的8个钩子函数    ---》当执行到那,就会执行某个钩子函数
	
beforeCreate	    创建Vue实例之前调用
created	            创建Vue实例成功后调用(可以在此处发送异步请求后端数据)
beforeMount	        渲染DOM之前调用
mounted	            渲染DOM之后调用
beforeUpdate	   重新渲染之前调用(数据更新等操作时,控制DOM重新渲染)
updated	           重新渲染完成之后调用
beforeDestroy	   销毁之前调用
destroyed	       销毁之后调用




# AOP 面向切面编程   ----》
# OOP 面向对象编程
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>
</head>
<body>
<div id="app">
    <button @click="handleShow">点我组件显示和消失</button>
    <Child v-if="show"></Child>

</div>

</body>
<script>
    // 创建一个组件
    Vue.component('Child', {
        template: `
          <div>
          <h1>{{ name }}</h1>
          <button @click="handleClick">点我看美女</button>
          </div>
        `,
        data() {
            return {
                name: 'lqz',
                t:'',
            }
        },
        methods: {
            handleClick() {
                alert('美女')
            }
        },
        beforeCreate(){
            console.log('beforeCreate')
        },
        created(){
            console.log('created')
            console.log('这个用的多,只要创建,data变量就初始化完成了,一般是从后端获取到的,在此处发送ajax请求')
            // 延迟任务,延迟几秒执行某个函数
            // setTimeout(()=>{
            //     alert('lqz is handsome')
            // },3000)

            // 定时任务,每个几秒,执行一次
            this.t=setInterval(()=>{
                console.log('3s结束了')
            },3000)
        },
        beforeMount(){
            console.log('beforeMount')
        },
        mounted(){
            console.log('mounted')
        },
        beforeUpdate(){
            console.log('beforeUpdate')
        },
        updated(){
            console.log('updated')
        },
        beforeDestroy(){
            console.log('beforeDestroy')
            console.log('可能会有,组件销毁,清理资源')
            clearInterval(this.t)
            this.t=null
        },
        destroyed(){
            console.log('destroyed')
        }

    })


    new Vue({
        el: '#app',
        data: {
            show: false,
        },
        methods:{
            handleShow(){
                this.show=!this.show
            }
        }
    })
</script>
</html>

8 vue与后端交互

# 向后端发送ajax请求----》jq的ajax方法
	-方案一:jq的ajax----》在vue中不推荐
    -方案二:js原始官方 fetch方法
    -方案三:axios 第三方
    
    
# django
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="./js/vue.js"></script>
</head>
<body>
<div id="app">
    <button @click="handleClick">点我向后端发请求,获取用户信息</button>
    <br>
    用户名:{{name}}
    <br>
    年龄是:{{age}}


</div>
</body>
<script>
    new Vue({
        el: '#app',
        data: {
            name: '',
            age: ''
        },
        methods: {
            // handleClick() {
            //     // 发送ajax请求  使用jq的ajax
            //     $.ajax({
            //         'url': 'http://127.0.0.1:5000/index',
            //         'type': 'get',
            //         success: data => {
            //             this.name = data.name
            //             this.age = data.age
            //         }
            //     })
            // }

            // handleClick() {
            //     // 发送ajax请求--使用原始的fetch
            //     fetch('http://127.0.0.1:5000/index').then(res => res.json()).then(res => {
            //         console.log(res)
            //         this.name = res.name
            //         this.age = res.age
            //     })
            //     // fetch('http://127.0.0.1:5000/index').then(function (res){return res.json()})
            // }
     
            handleClick() {
                // 发送ajax请求--使用axios
                axios.get('http://127.0.0.1:5000/index').then(res => {
                    console.log(res.data)
                    this.name = res.data.name
                    this.age = res.data.age
                })
            }
        }
    })


</script>
</html>

小电影案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="./js/vue.js"></script>
</head>
<body>
<div id="app">

    <ul>
        <li v-for="item in film_data ">
            <h2>电影名字:{{item.name}}</h2>
            <p>电影介绍:{{item.synopsis}}</p>
            <img :src="item.poster" alt="" width="100px" height="300px">
        </li>
    </ul>


</div>
</body>
<script>
    new Vue({
        el: '#app',
        data: {
            film_data:[]
        },
        created(){
              axios.get('http://127.0.0.1:5000/film').then(res => {
                    console.log(res.data)
                    this.film_data = res.data.data.films
                })

        }
    })


</script>
</html>

flask

from flask import Flask, jsonify
import json

app = Flask(__name__)


@app.route('/index')
def index():
    res = jsonify({'name': '彭于晏', 'age': 99})
    res.headers['Access-Control-Allow-Origin'] = '*'
    return res


@app.route('/film')
def film():
    with open('./data.json', 'r', encoding='utf-8')as f:
        res = json.load(f)

    res=jsonify(res)
    res.headers['Access-Control-Allow-Origin'] = '*'
    return res


if __name__ == '__main__':
    app.run()

标签:vue,name,price,number,购物车,item,checkGroup,单选,data
来源: https://www.cnblogs.com/chunyouqudongwuyuan/p/16420761.html