前端:index.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
from flask import Flask # 这里用轻量级的Flask框架来测试
app = Flask(__name__)
@app.route('/')
def index():
print('请求来了')
return 'Hello World'
if __name__ == '__main__':
app.run()
这里可以看出:前端向后端成功发送了请求,后端也成功响应了,但是前端却报错了
这是因为:跨域问题的存在,浏览器检测到前端和后端不是来自同一个域,所以认为这是不安全的,所以就拦截了该资源的传递
想要解决这个问题,就要实现:CORS
,也就是 跨域资源共享
前端:index.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
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()
json文件:file.json
{
"name": "Darker",
"age": "18",
"gender": "male"
}
前端:index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue与后端交互 - jsontitle>
<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
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
介绍
提供了一个
JavaScript
接口,用于访问和操纵HTTP
管道的一些具体部分,例如请求和响应
它还提供了一个全局
fetch()
方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源
② fetch
基本格式
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
json
文件:file.json
{
"name": "Darker",
"age": "18",
"gender": "male"
}
后端:main.py
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 lang="en">
<head>
<meta charset="UTF-8">
<title>Vue与后端交互 - fetchtitle>
<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>
Axios
是一个基于 promise
的 HTTP
库,可以用在浏览器和 node.js
中axios
官网:http://www.axios-js.com/
json
文件:film.json
(这里只是一部分,原代码太多了…)
{
"data":{
"films":[
{
"actors":[
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/45deca0f886633f1a8902f7eece4248a.jpg",
"name":"林超贤",
"role":"导演"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/ff8f5bfd455e660298452c0546bb23d5.jpg",
"name":"辛芷蕾",
"role":"方宇凌"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/f27b94579d10d3131b476ec6c63a2722.jpg",
"name":"蓝盈莹",
"role":"演员"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/0a30de65731f3ddc5ce5d5915c8d9d49.jpg",
"name":"彭于晏",
"role":"高谦"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/728944e292dc6e8161acd7d5344d361c.jpg",
"name":"王彦霖",
"role":"赵呈"
}
],
"category":"剧情|灾难",
"director":"林超贤",
"filmId":4836,
"filmType":{
"name":"2D",
"value":1
},
"grade":"7.8",
"isPresale":true,
"isSale":false,
"item":{
"name":"2D",
"type":1
},
"language":"汉语普通话",
"name":"紧急救援",
"nation":"中国大陆",
"poster":"https://pic.maizuo.com/usr/movie/c14a70858e2bda9c2bc8eaa7bfa0e2aa.jpg",
"premiereAt":1579910400,
"runtime":100,
"synopsis":"《紧急救援》是由林超贤导演,彭于晏、王彦霖、辛芷蕾、蓝盈莹出演的中国首部海上救援打捞题材的作品。筹备过程中,导演林超贤带领团队实地勘察选址,力求打造更劲爆,更震撼的场景设置,本次与奥斯卡最佳摄影鲍德熹,《泰坦尼克号》美术指导Martin Laing等国际顶级制作团队的强强联合,预示着电影将成为首部打开国际市场的华语救援题材作品,也势必会成为又一部华语电影的标杆之作。",
"timeType":3,
"videoId":"XNDIyODM2NjE4OA=="
},
{
"actors":[
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/c8722df42d08942db01c2a262f576950.jpg",
"name":"易小星",
"role":"导演"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/9627d1ebac2b4b12a06fd1623a62af99.jpg",
"name":"彭昱畅",
"role":"肖翔"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/4b6da2deabe5dc7883321bb17372c25b.jpg",
"name":"乔杉",
"role":"周东海"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/7efe813dd79280f236b8d1286cdc313c.jpg",
"name":"卜冠今",
"role":"周希希"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/f244a95cdcd64625a50069bd64db49c2.jpg",
"name":"苇青",
"role":"王素芬"
}
],
"category":"喜剧|动作",
"director":"易小星",
"filmId":5266,
"filmType":{
"name":"2D",
"value":1
},
"grade":"7.2",
"isPresale":true,
"isSale":false,
"item":{
"name":"2D",
"type":1
},
"language":"",
"name":"沐浴之王",
"nation":"中国大陆",
"poster":"https://pic.maizuo.com/usr/movie/e6aabffd040bda24f483bcc95ed79e62.jpg",
"premiereAt":1607644800,
"runtime":102,
"synopsis":"在一次搓澡服务中,富二代肖翔(彭昱畅 饰)和搓澡工周东海(乔杉 饰)发生矛盾,让周东海面临生活困境。肖翔因跳伞事故被送到医院记忆全失,周东海恰巧撞见,心生一计,骗肖翔是自己的弟弟并骗回周家澡堂当搓澡工,于是一个富二代开始了一段终身难忘的搓澡生涯……",
"timeType":3,
"videoId":""
},
{
"actors":[
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/168e82b3c4ec676ca577cb99e5a9ee06.jpg",
"name":"派蒂·杰金斯",
"role":"导演"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/c4cfadaaab8f81ebaf3bdc7aa30fac49.jpg",
"name":"盖尔·加朵",
"role":"戴安娜·普林斯 / 神奇女侠 Diana Prince / Wonder Woman"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/6e0a82c6efac00bfb6b7c1b4bb46eaa9.jpg",
"name":"克里斯·派恩",
"role":"史蒂夫·特雷弗 Steve Trevor"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/79a97235ee2f33741b63eafc2f34658e.jpg",
"name":"克里斯汀·韦格",
"role":"芭芭拉·密涅瓦 Cheetah"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/13c53574fc0c4b13b99e966af5af7e9d.jpg",
"name":"佩德罗·帕斯卡",
"role":"马克斯维尔·劳德 Max Lord"
}
],
"category":"动作|奇幻|冒险",
"director":"派蒂·杰金斯",
"filmId":5287,
"filmType":{
"name":"3D",
"value":2
},
"isPresale":true,
"isSale":false,
"item":{
"name":"3D",
"type":2
},
"language":"",
"name":"神奇女侠1984",
"nation":"美国",
"poster":"https://pic.maizuo.com/usr/movie/4f84f5a48560f5b14b0fac7768da4e05.jpg",
"premiereAt":1608249600,
"runtime":151,
"synopsis":"神奇女侠的全新大银幕冒险来到了1980年代。神奇女侠戴安娜在华盛顿的自然历史博物馆过着与普通人无异的生活,然而在阻止了一场看似平常的劫案后,身边的一切都发生了变化。在强大的神力诱惑下,两位全新劲敌悄然出现——与神奇女侠“相爱相杀”的顶级掠食者豹女,以及掌控着能改变世界力量的麦克斯·洛德,一场惊天大战在所难免。另外一边,旧爱史蒂夫突然“死而复生”,与戴安娜再续前缘,然而浪漫感动之余,史蒂夫的回归也疑窦丛生。",
"timeType":3,
"videoId":""
},
{
"actors":[
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/6735332cb677645542c2f136eb37e561.jpg",
"name":"邱礼涛",
"role":"导演"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/ca47cd961fe0be0c91149f6bcca2f13d.jpg",
"name":"刘德华",
"role":"潘乘风"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/82a5d97e318c447133cd6c8262cee846.jpg",
"name":"刘青云",
"role":"董卓文"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/e776871fe75f0367aa60957457a6f96c.jpg",
"name":"倪妮",
"role":"庞玲"
},
{
"avatarAddress":"https://pic.maizuo.com/usr/movie/dd120eb1f6bda9f3b9c9e4c49785d0ce.jpg",
"name":"谢君豪",
"role":"演员"
}
],
"category":"动作|犯罪",
"director":"邱礼涛",
"filmId":5257,
"filmType":{
"name":"2D",
"value":1
},
"isPresale":true,
"isSale":false,
"item":{
"name":"2D",
"type":1
},
"language":"",
"name":"拆弹专家2",
"nation":"中国大陆,中国香港",
"poster":"https://pic.maizuo.com/usr/movie/4a2bec5290b94f7eb597913727b21df6.jpg",
"premiereAt":1608768000,
"runtime":0,
"synopsis":"香港某处发生爆炸案,前拆弹专家潘乘风(刘德华 饰)因昏迷于现场,被警方怀疑牵涉其中。苏醒后的潘乘风只能一边逃亡一边查明真相,然而,他的好友董卓文(刘青云 饰)和他的前女友庞玲(倪妮 饰)却给他讲述了两段截然不同的经历。有计划的爆炸案接二连三发生,真相却越来越扑朔迷离……",
"timeType":3,
"videoId":""
}
],
"total":47
},
"msg":"ok",
"status":0
}
后端:main.py
import json
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/film')
def index():
print('请求来了')
with open('film.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 lang="en">
<head>
<meta charset="UTF-8">
<title>Vue与后端交互title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js">script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.min.js">script>
head>
<body>
<div id="box">
<button @click="handleClick">加载电影数据button>
<p>加载的数据:p>
<ul>
<li v-for="item in dataList">
<p>电影:{{item.name}}p>
<p>导演:{{item.director}}p>
<img :src="item.poster" alt="">
li>
ul>
div>
body>
<script>
let vm = new Vue({
el: '#box',
data: {
dataList: []
},
methods: {
handleClick() {
axios.get("http://127.0.0.1:5000/film/").then(res => {
console.log(res.data.data.films) // axios 自动包装data属性 res.data
this.dataList = res.data.data.films
}).catch(err => {
console.log(err);
})
}
}
})
script>
html>
计算属性是基于它们的依赖进行缓存的
计算属性只有在它的相关依赖发生改变时才会重新求值
计算属性就像
Python
中的property
,可以把方法/函数伪装成属性
<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>
head>
<body>
<div id="box">
模板插值:
{{myText.substring(0,1).toUpperCase()+myText.substring(1)}}
<p>普通方法:{{getNameMethod()}}p>
<p>计算属性:{{getName}}p>
div>
body>
<script>
var vm = new Vue({
el: '#box',
data: {
myText: 'darker',
},
computed: {
getName() { // 依赖的状态改变了,会重新计算
return this.myText.substring(0, 1).toUpperCase() + this.myText.substring(1)
}
},
methods: {
getNameMethod() {
return this.myText.substring(0, 1).toUpperCase() + this.myText.substring(1)
}
}
})
script>
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>
head>
<body>
<div id="box">
<p><input type="text" v-model="myText" placeholder="请输入要筛选的内容:">p>
<ul>
<li v-for="data in newList">{{data}}li>
ul>
div>
body>
<script>
var vm = new Vue({
el: '#box',
data: {
myText: '',
dataList: ['a', 'at', 'atom', 'be', 'beyond', 'cs', 'csrf'],
},
computed: {
newList() {
return this.dataList.filter(item => {
return item.indexOf(this.myText) > -1 // 返回索引大于1的元素:>-1 就表示包含在其中
})
}
}
})
script>
html>
其实呢不只是
vue
,react
中在执行列表渲染时也会要求给每个组件添加key
这个属性
key
简单点来说就是唯一标识,就像ID
一样唯一性
要知道,
vue
和react
都实现了一套虚拟DOM
,使我们可以不直接操作DOM
元素,只操作数据便可以重新渲染页面
而隐藏在背后的原理便是其高效的Diff
算法
key
值比较:出现新的key
就插入同组(循环中,尽量加key
,让key
值唯一)<div id="box">
<div v-if="isShow">111div>
<p v-else>222p>
<div v-if="isShow">111div>
<div v-else>222div>
div>