5.5 再次修改MobileGame

第 36 节 / 共 81 节 课程:前后端穿透

现在的问题来了,GameFrame的数据是哪里提供的?在GameFrame内部查询数据,还是在MobileGame查询?

如果是GameFrame内部自行查询数据,那么就要由外部(也就是使用GameFrame的页面MobileGame)给出查询的关键字,例如“角色扮演”,“回合卡牌”;如果是MobileGame查询,那么就由MobileGame一次查询出所有的数据,这里采用此方案。

一个游戏栏(GameFrame)的数据在数据库是这样的,如图5-20所示:

GameFrame表的结构
图5-20 GameFrame表的结构

id是主键

game_type是游戏的类型

game_num就是展示的数量,5或者10

mode是展示方式,game_list是横排,game_item是竖排

tab_name是左上角显示的名字

css是用来控制内部展示的游戏的外观

http的接口是:https://www.codessp.cn/api/gameFrames

把数据复制到www.json.cn解析,如图5-21所示:

gameFrame接口返回的json数据
图5-21 gameFrame接口返回的json数据

返回的数据中的data就是我们要的游戏框架GameFrame所需要的数据。要记住,查询GameFrame是在MobileGame组建里进行。代码5-8在MobileGame.vue里:

<script>
import GameFrame from './GameFrame.vue';
import axios from 'axios';
export default {
    name: "MobileGame",
    components: { GameFrame },
    data(){
        return{
            gameFrames:[]
        }
    },
    mounted: function () {
        window.test = this.test;
        let url = "https://www.codessp.cn/api/gameFrames";
        axios({
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            method: "get",
            url: url,
            params: ''
        }).then((response) => {
            this.gameFrames = response.data.data;
            console.log(this.gameFrames);
        });
    }
}
</script>

代码5-8 修改MobileGame.vue的script部分

代码5-8比起代码5-7增加了几个部分:

增加了变量gameFrames,这是一个数组;

增加axios的import语句;

增加了用axios获取所有gameFrame数据的代码,写在mounted函数里。

此时启动项目,访问http://localhost:8080/#/mobile,页面不会有变化,因为获取数据后并没有用在显示部分(template),仅仅用console.log打印,打印结果需要在浏览器按下F12查看,如图5-22所示:

在浏览器查看this.gameFrames的值
图5-22 在浏览器查看this.gameFrames的值

接下来修改MobileGame的template部分。MobileGame组件的变量gameFrames是一个数组,里面含有多个数据,用循环逐个显示出来。现在MobileGame的template部分应该是如图5-23所示:

MobileGameGame的template部分
图5-23 MobileGameGame的template部分

现在GameFrame数据已经有了(数据gameFames里),所以只需要把图5-23的单个GameFrame的部分用循环替代,为了方便后面开发对比,可以保留一个游戏栏,也就是代码第59行到152行,152行后面的可以删除。

循环显示GameFrame的代码在5.2节的代码5-3就出现过了,最后MobileGame.vue修改后的代码如图5-24所示:

MobileGame.vue的template部分修改后的代码
图5-24 MobileGame.vue的template部分修改后的代码

《前后端穿透》课程目录

按教材顺序从 Vue 前端讲到 Spring Boot 后端:模板、组件、路由、axios、Controller、JPA、文件上传、Nginx 部署,最后完成学习平台实训。10 章 71 节,配 220 张操作截图与可直接运行的代码。