vue购物车案例、v-model进阶、与后端交互

一 购物车案例

- 结算

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>购物车结算</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        table, td {
            border: 1px solid black;
            text-align: center;
        }
    </style>
</head>
<body>
<div id="box">
    <table>
        <tr>
            <td>商品名称</td>
            <td>价格</td>
            <td>数量</td>
            <td>选择</td>
        </tr>
        <tr v-for="item in dataList">
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
            <td>{{item.number}}</td>
            <td><input type="checkbox" :value="item" v-model="checkGroup"></td>
        </tr>
    </table>
    <br>已选商品:{{checkGroup}}
    <br>总价:{{getPrice()}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: [
                {name: '今瓶没', price: 99, number: 2},
                {name: '西柚记', price: 59, number: 1},
                {name: '水壶转', price: 89, number: 5},
            ],
            checkGroup: [],
        },
        methods: {
            getPrice() {
                let sum_price = 0
                for (i in this.checkGroup) {    // 这里的 i 是索引
                    sum_price += this.checkGroup[i]['number'] * this.checkGroup[i]['price']
                }
                return sum_price
            }
        }
    })
</script>
</html>

- 全选/全不选

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全选/全不选</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        table, td {
            border: 1px solid black;
            text-align: center;
        }
    </style>
</head>
<body>
<div id="box">
    <table>
        <tr>
            <td>商品名称</td>
            <td>价格</td>
            <td>数量</td>
            <td>全选/全不选<input type="checkbox" v-model="allChecked" @change="checkAll"></td>
        </tr>
        <tr v-for="item in dataList">
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
            <td>{{item.number}}</td>
            <td><input type="checkbox" :value="item" v-model="checkGroup" @change="checkOne"></td>
        </tr>
    </table>
    <br>已选商品:{{checkGroup}}
    <br>总价:{{getPrice()}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: [
                {name: '今瓶没', price: 99, number: 2},
                {name: '西柚记', price: 59, number: 1},
                {name: '水壶转', price: 89, number: 5},
            ],
            checkGroup: [],
            allChecked: false,
        },
        methods: {
            getPrice() {
                let sum_price = 0
                for (i in this.checkGroup) {    // 这里的 i 是索引
                    sum_price += this.checkGroup[i]['number'] * this.checkGroup[i]['price']
                }
                return sum_price
            },
            checkAll() {
                if (this.checkGroup.length > 0) {
                    this.checkGroup = []
                } else {
                    this.checkGroup = this.dataList
                }
            },
            checkOne() {
                // if (this.checkGroup.length === this.dataList.length) {
                //     this.allChecked = true
                // } else {
                //     this.allChecked = false
                // }
                this.allChecked = this.checkGroup.length === this.dataList.length;
            }
        }
    })
</script>
</html>

- 数量加减

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>控制加减</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="row">
    <div id="box" class="col-md-4 offset-md-1 text-center mt-5 ">
        <table class="table table-bordered">
            <thead>
            <tr>
                <th scope="col">商品名称</th>
                <th scope="col">单价</th>
                <th scope="col">数量</th>
                <th scope="col">全选/全不选 <input type="checkbox" v-model="allChecked" @change="checkAll"></th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="item in dataList">
                <td>{{item.name}}</td>
                <td>{{item.price}}</td>
                <td>
                    <button class="btn link btn-sm" @click="reduceNum(item)">-</button>
                    {{item.number}}
                    <button class="btn link btn-sm" @click="item.number++">+</button>
                </td>
                <td><input type="checkbox" :value="item" v-model="checkGroup" @change="checkOne"></td>
            </tr>
            <tr class="text-left">
                <td colspan="4">总价:{{getPrice()}}
            </tr>
            </tbody>
        </table>
    </div>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: [
                {name: '今瓶没', price: 99, number: 1},
                {name: '西柚记', price: 59, number: 1},
                {name: '水壶转', price: 89, number: 1},
            ],
            checkGroup: [],
            allChecked: false,
        },
        methods: {
            getPrice() {
                let sum_price = 0
                for (i in this.checkGroup) {
                    sum_price += this.checkGroup[i]['number'] * this.checkGroup[i]['price']
                }
                return sum_price
            },
            checkAll() {
                if (this.checkGroup.length > 0) {
                    this.checkGroup = []
                } else {
                    this.checkGroup = this.dataList
                }
            },
            checkOne() {
                // if (this.checkGroup.length === this.dataList.length) {
                //     this.allChecked = true
                // } else {
                //     this.allChecked = false
                // }
                this.allChecked = this.checkGroup.length === this.dataList.length;
            },
            reduceNum(item) {
                if (item.number === 1) {
                    item.number = 1
                } else {
                    item.number--
                }
            }
        }
    })
</script>
</html>

二:v-model进阶

v-model 之 lazy、number、trim

  • lazy:等待input框的数据绑定时区焦点之后再变化
  • **number:**数字开头,只保留数字,后面的字母不保留;字母开头,都保留
  • **trim:**去除首位的空格
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-model 之 lazy、number、trim</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <input type="text" v-model="myText1" placeholder="normal"> {{myText1}}
    <br>
    <input type="text" v-model.lazy="myText2" placeholder="lazy"> {{myText2}}
    <br>
    <input type="text" v-model.number="myText3" placeholder="number"> {{myText3}}
    <br>
    <input type="text" v-model.trim="myText4" placeholder="trim"> {{myText4}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            myText1: '',
            myText2: '',
            myText3: '',
            myText4: '',
        },
    })
</script>
</html>

三 与后端交互 - ajax

版本1 - 出现了跨域问题

前端:index.html
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue与后端交互 - 出现了跨域问题</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <button @click="handleClick">加载数据</button>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {},
        methods: {
            handleClick() {
                $.ajax({
                    url: 'http://127.0.0.1:5000/',    // 发送请求的url,本地的5000端口,是flask的默认端口
                    method: 'get',
                    success: (data) => {
                        console.log(data)
                    }
                })
            }
        }
    })
</script>
</html>
后端:main.py
python 复制代码
from flask import Flask    # 这里用轻量级的Flask框架来测试

app = Flask(__name__)


@app.route('/')
def index():
    print('请求来了')
    return 'Hello World'


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

这里可以看出:前端向后端成功发送了请求,后端也成功响应了,但是前端却报错了

这是因为:跨域问题的存在,浏览器检测到前端和后端不是来自同一个,所以认为这是不安全的,所以就拦截了该资源的传递

想要解决这个问题,就要实现:CORS ,也就是 跨域资源共享

版本2 - 解决了跨域问题

前端:index.html
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue与后端交互 - 解决了跨域问题</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <button @click="handleClick">加载数据</button>
    <p>加载的数据:{{myText}}</p>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            myText: ''
        },
        methods: {
            handleClick() {
                $.ajax({
                    url: 'http://127.0.0.1:5000/',
                    method: 'get',
                    success: (data) => {
                        console.log(data)
                        this.myText = data
                    }
                })
            }
        }
    })
</script>
</html>
后端:main.py
python 复制代码
from flask import Flask, make_response

app = Flask(__name__)


@app.route('/')
def index():
    print('请求来了')
    res = make_response('Hello World')
    res.headers['Access-Control-Allow-Origin'] = '*'    # 访问控制允许的源 设置为全部
    return res


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

版本3 - 后端读取json文件传到前端

json文件:file.json
python 复制代码
{
  "name": "Darker",
  "age": "18",
  "gender": "male"
}
前端:index.html
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue与后端交互 - json</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <button @click="handleClick">加载数据</button>
    <p>加载的数据:{{myText}}</p>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            myText: ''
        },
        methods: {
            handleClick() {
                $.ajax({
                    url: 'http://127.0.0.1:5000/',
                    method: 'get',
                    success: (data) => {
                        console.log(data)
                        this.myText = data
                    }
                })
            }
        }
    })
</script>
</html>
后端:main.py
python 复制代码
import json

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/')
def index():
    print('请求来了')
    with open('file.json', mode='rt', encoding='utf-8') as f:
        dic = json.load(f)
    res = jsonify(dic)
    res.headers['Access-Control-Allow-Origin'] = '*'
    return res


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

fetch

1.简介

① fetch介绍

提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应

它还提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源

② fetch基本格式
javascript 复制代码
fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

2.实例

json文件:file.json
python 复制代码
{
  "name": "Darker",
  "age": "18",
  "gender": "male"
}
后端:main.py
python 复制代码
import json

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/')
def index():
    print('请求来了')
    with open('file.json', mode='rt', encoding='utf-8') as f:
        dic = json.load(f)
    res = jsonify(dic)
    res.headers['Access-Control-Allow-Origin'] = '*'
    return res


if __name__ == '__main__':
    app.run()
前端:index.html
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue与后端交互 - fetch</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <button @click="handleClick">加载数据</button>
    <p>加载的数据:</p>
    <ul>
        <li >姓名:{{name}}</li>
        <li >年龄:{{age}}</li>
        <li >性别:{{gender}}</li>
    </ul>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            name:'',
            age: '',
            gender: ''
        },
        methods: {
            handleClick() {
                fetch('http://127.0.0.1:5000/').then(response => {
                    return response.json()
                }).then(json => {
                    console.log('从后端获取的json数据', json)   // success 获取的数据
                    this.name = json.name
                    this.age = json.age
                    this.gender = json.gender
                }).catch(ex => {
                    console.log('出现了异常', ex)    // 抛出异常
                })
            }
        }
    })
</script>
</html>
相关推荐
陌小呆^O^6 分钟前
Cmakelist.txt之win-c-udp-server
c语言·开发语言·udp
brief of gali8 分钟前
记录一个奇怪的前端布局现象
前端
计算机毕设指导611 分钟前
基于 SpringBoot 的作业管理系统【附源码】
java·vue.js·spring boot·后端·mysql·spring·intellij-idea
Gu Gu Study13 分钟前
枚举与lambda表达式,枚举实现单例模式为什么是安全的,lambda表达式与函数式接口的小九九~
java·开发语言
时光の尘28 分钟前
C语言菜鸟入门·关键字·float以及double的用法
运维·服务器·c语言·开发语言·stm32·单片机·c
以后不吃煲仔饭41 分钟前
Java基础夯实——2.7 线程上下文切换
java·开发语言
进阶的架构师42 分钟前
2024年Java面试题及答案整理(1000+面试题附答案解析)
java·开发语言
前端拾光者1 小时前
利用D3.js实现数据可视化的简单示例
开发语言·javascript·信息可视化
程序猿阿伟1 小时前
《C++ 实现区块链:区块时间戳的存储与验证机制解析》
开发语言·c++·区块链
Json_181790144801 小时前
电商拍立淘按图搜索API接口系列,文档说明参考
前端·数据库