人生若只如初见

WXY

Vue.js实现带有动态数据的单页html

2022-11-01

前言

有个群友让帮忙写个单页html调用接口获取数据
为啥不用jQuery呢? 对自己好一点,当然用vue.js了
写好了顺带记录下,方便自己下次回忆。

效果图

都是最基础最简单的东西

vuedemo

完整页面代码

一共调用了三个数据接口 自行替换,并修改数据对应字段

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>测试</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
  <select style="margin-right:50px;" v-model="select1">
    <option value="NONE">未选择</option>
    <option v-for="(options) in list1" :value="options">
      {{ options }}
    </option>
  </select>

  <select style="margin-right:50px;" v-model="select2">
    <option value="NONE">未选择</option>
    <option v-for="(options) in list2" :value="options">
      {{ options }}
    </option>
  </select>

  <button @click="btn">按钮</button>

  <br/>

  <table style="margin-top:50px;" border="1">
    <tr>
      <td>name</td>
      <td>className</td>
      <td>iphone</td>
      <td>school</td>
      <td>teacherName</td>
    </tr>
    <tr v-for="(options) in tableList" :value="options">

      <td> {{ options.name }}</td>
      <td> {{ options.className }}</td>
      <td> {{ options.iphone }}</td>
      <td> {{ options.school }}</td>
      <td> {{ options.teacherName }}</td>
    </tr>
  </table>

</div>

</body>
</html>

<script>
  const {createApp} = Vue

  createApp({
    data() {
      return {
        select1: "",
        select2: "",
        list1: [],
        list2: [],
        tableList: []
      }
    },
    created: function () {
      axios.get('接口地址', {}).then((res) => {
        this.list1 = res.data
        console.log('数据1:', res);
      })

      axios.get('接口地址', {}).then((res) => {
        this.list2 = res.data
        console.log('数据2:', res);
      })
    },
    methods: {
      btn() {
        if (this.select1 == 'NONE' || this.select1 == '' || this.select2 == 'NONE' || this.select2 == '') {
          alert('下拉框未选择')
          return;
        }
        axios.get('接口地址?num=' + this.select1 + '&s=' + this.select2, {}).then((res) => {
          this.tableList = res.data
          console.log('table数据:', res);
        })
      },
    }

  }).mount('#app')
</script>