chaihongjun.me

vue3获取异步数据并渲染模板demo

假设条件

使用axios从服务器获取数据,返回的数据:

{"status":200,"msg":"获取图书列表成功","data":[{"id":1,"bookname":"西游记","author":"吴承恩","publisher":"北京图书出版社"},{"id":2,"bookname":"西游记","author":"吴承恩","publisher":"北京图书出版社"},{"id":3,"bookname":"红楼梦","author":"曹雪芹","publisher":"上海图书出版社"},{"id":239,"bookname":"水浒传续集","author":"施耐庵","publisher":"上海图书出版社"},{"id":240,"bookname":"金瓶梅","author":"兰陵笑笑生","publisher":"香江出版社出版"}]}

方法一:使用ref

组件代码:

<script setup>
  // getBooks获取的是服务器接口数据{status,data,msg}
  // 实际使用的数据是data属性
  import { getBooks } from "@/request/api.js";
  import { ref } from "vue";
  // ref初始化一个变量,用于接收接口数据data属性
  let books = ref(null);
  async function handler() {
    // await 后面的函数返回的是一个promise对象,我们只需要其中data属性的值,所以做了解构
    let { data } = await getBooks();
    // 由于是使用ref,所以javascript中需要给.value赋值
    books.value = data;
    console.log("books:", books);
  }
</script>
<template>
首页
<button @click="handler">获取书籍信息</button>
<hr />
<table border="1">
  <tr>
    <td>序号</td>
    <td>书名</td>
    <td>作者</td>
    <td>出版社</td>
  </tr>
  <!-- 模板内直接访问,不需要使用 .value 方式访问 -->
  <tr v-for="book in books" :key="book.id">
    <td>{{ book.id }}</td>
    <td>{{ book.bookname }}</td>
    <td>{{ book.author }}</td>
    <td>{{ book.publisher }}</td>
  </tr>
  </table>
</template>

方法二:使用reactive

组件代码:

<script setup>
  // getBooks获取的是服务器接口数据{status,data,msg}
  // 实际使用的数据是data属性
  import { getBooks } from "@/request/api.js";
  import { reactive } from "vue";
  // reactive初始化一个变量,用于接收接口数据data属性
  let result = reactive({ books: [] });
  async function handler() {
    // await 后面的函数返回的是一个promise对象,我们只需要其中data属性的值,所以做了解构
    let { data } = await getBooks();
    result.books = data;
  }
</script>
<template>
首页
<button @click="handler">获取书籍信息</button>
<hr />
<table border="1">
  <tr>
    <td>序号</td>
    <td>书名</td>
    <td>作者</td>
    <td>出版社</td>
  </tr>
  <tr v-for="book in result.books" :key="book.id">
    <td>{{ book.id }}</td>
    <td>{{ book.bookname }}</td>
    <td>{{ book.author }}</td>
    <td>{{ book.publisher }}</td>
  </tr>
  </table>
</template>

从美观度来说,使用ref的方法模板显得更简洁一些


知识共享许可协议本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。作者:chaihongjun»