![3cfad4c3010bd23b72839991e81b9b9f.png](https://img-blog.csdnimg.cn/img_convert/3cfad4c3010bd23b72839991e81b9b9f.png)
上一篇介绍了Flask和Vue安装和配置,本篇将演示如果在vue app中获取和展示从flask app得到的内容。
创建前端页面
本节展示如何创建一个前端页面。
在client/src/components
文件夹下,创建一个文件Door.vue
:
<template>
<div>
<p>{{ msg }}</p>
</div>
</template>
<script>
export default {
name: 'Door',
data() {
return {
msg: '芝麻开门',
};
},
};
</script>
修改文件client/src/router/index.js
,将/open
映射到Door
模块:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Door from '../components/Door.vue';
Vue.use(VueRouter)
const routes = [
{
path: '/open',
name: 'Door',
component: Door
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
修改client/src/App.vue
,删掉无关内容,只留下以下内容:
<template>
<div id="app">
<router-view/>
</div>
</template>
在浏览器中打开http://localhost:8080/open,可以看到页面上显示芝麻开门
。
连接前后端
本节演示如何连接前端的vue app和后端的Flask app
可以通过第三方包axios
来连接前后端。使用npm
安装axios
(运行npm
命令之前,确保当前路径是client
文件夹下):
npm install axios --save
更改client/src/components/Door.vue
中的<script>
部分:
<script>
import axios from 'axios';
export default {
name: 'Door',
data() {
return {
msg: '',
};
},
methods: {
getMessage() {
const path = 'http://localhost:5000/open';
axios.get(path)
.then((res) => {
this.msg = res.data;
})
.catch((error) => {
// eslint-disable-next-line
console.error(error);
});
},
},
created() {
this.getMessage();
},
};
</script>
此时,在一个终端中启动vue app:
cd client
npm run serve
在另一个终端中启动flask app:
conda activate flask
cd server
python app.py
再在浏览器中访问http://localhost:8080/open,此时可以看到页面上显示芝麻开门!
(带感叹号!
说明是从后端的flask app得到的数据,可以通过浏览器访问http://localhost:5000/open得到验证,在上一节中的例子是没有感叹号的)。(本例中,后端的缺省端口号是5000
,前端的缺省端口号是8080
。)
添加Bootstrap样式
Bootstrap是相当流行的CSS框架,本示例中使用Bootstrap来美化页面外观。可以通过npm
来安装(运行npm
命令之前,确保当前路径是client文件夹下):
npm install bootstrap --save
忽略有关popper.js的警告,不要安装popper.js 。
在client/src/main.js
中引入Bootstrap,在文件最顶上加上:
import 'bootstrap/dist/css/bootstrap.css';
为了验证Bootstrap正常启用,可以通过以下方式验证。修改client/src/components/Door.vue
中的<template>
部分:
<template>
<div class="container">
<button type="button" class="btn btn-primary">{{ msg }}</button>
</div>
</template>
此时再在浏览器中访问或刷新http://localhost:8080/open,可以看到芝麻开门!
的样式已经变成一个按钮。
![f0b7e075b1b0390aba4a3785057eea45.png](https://img-blog.csdnimg.cn/img_convert/f0b7e075b1b0390aba4a3785057eea45.png)