与后端交互
axions发送ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../js/vue.js"></script>
<script src="../js/axios.js"></script>
</head>
<body>
<div class="app">
<h1>热映电影</h1>
<button @click="handleClick">点我</button>
<ul>
<li v-for="item in dataList">
<h2>名字:{{item.name}}</h2>
<h3>导演:{{item.director}}</h3>
<h3>类型:{{item.category}}</h3>
<p>简介:{{item.synopsis}}</p>
<img :src="item.poster" alt="" height="300px" width="200px">
</li>
</ul>
</div>
</body>
<script>
var vm = new Vue({
el: '.app',
data: {
dataList: []
},
methods: {
handleClick() {
//1 axios
axios.get('http://127.0.0.1:8000/api/').then(res => {
this.dataList = res.data.data.films
})
}
}
})
</script>
</html>
后端代码:
import json
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here.
class VueView(APIView):
def get(self, request):
# film.json为从https://m.maizuo.com/v5/?co=mzmovie#/films/nowPlaying爬取的json数据
with open('app01/film.json', 'r', encoding='utf-8') as f:
res_dict = json.load(f)
return Response(data=res_dict, headers={'Access-Control-Allow-Origin': '*'})
路由:
path('api/', views.VueView.as_view())
vue生命周期
从Vue实例创建开始到实例被销毁,总共经历了8个生命周期钩子函数(只要写了就会执行)
8个生命周期函数
beforeCreate 创建Vue实例之前调用
created 创建Vue实例成功之后调用,可以在此处发送异步请求后端数据
beforeMount 渲染DOM之前调用
mounted 渲染DOM之后调用
beforeUpdate 重新渲染之前调用,就是数据更新等操作时控制DOM重新渲染
updated 重新渲染完成之后调用
beforeDestory 销毁之前调用
destoryed 销毁之后调用
这8个钩子函数用的最多的就是created
beforeDestory作用
创建组件,created中启动一个定时器,组件被销毁使用beforeDestory销毁定时器