Skip to content

Vue.js 单文件组件入门(非 Node.js 环境) #133

Description

@JasonWu73

本文承接 Vue.js 组件入门 一文。

BookList.vue

<template>
  <dl>
    <dt>图书列表(单文件组件)</dt>
    <dd class="page">
      <a href="javascript:void(0);"
         v-for="num in totalPage"
         :class="{active: currentPage === num}"
         @click="currentPage = num"
      >第{{num}}页</a>
    </dd>
    <dd v-for="book in bookList">
      {{book.row_index}}. 《{{book.book_name}}》 - CN¥{{book.book_price}} - {{book.book_press}}
    </dd>
  </dl>
</template>

<script>
  // 注意:这里必须是以 CommonJS(Node.js) 的 `module.exports` 方式导出,而不能是 ES6 的 `export default`
  // 建议阅读:https://stackoverflow.com/questions/40294870/module-exports-vs-export-default-in-node-js-and-es6
  module.exports = {
    data() {
      return {
        bookList: [],
        bookTotal: 0,
        pageSize: 10,
        currentPage: 1
      };
    },
    created() {
      this.getBookList();
    },
    beforeUpdate() {
      this.getBookList();
    },
    computed: {
      totalPage() {
        // 每页 `pageSize` 条,有小数,则+1
        // 若列表长度为0,则显示1
        return Math.ceil(this.bookTotal / this.pageSize) || 1;
      }
    },
    methods: {
      getBookList() {
        axios.get(`/books?page=${this.currentPage}&page_size=${this.pageSize}`)
        .then(response => {
          const {book_list: bookList, total} = response.data.result;
          this.bookList = bookList;
          this.bookTotal = total;
        });
      }
    }
  }
</script>

<style scoped>

</style>

index.html

<!doctype html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Axios & Mock.js</title>

  <style>
    .page a {
      margin-left: 15px;
    }

    .page a.active {
      color: red;
    }
  </style>
</head>
<body>

<div id="app">
  <book-list></book-list>
</div>

<script src="https://cdn.bootcdn.net/ajax/libs/Mock.js/1.0.1-beta3/mock-min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://unpkg.com/http-vue-loader"></script>

<script src="./js/api.js"></script>

<script type="module">

  // 注册组件 - 全局注册
  //Vue.component('book-list', httpVueLoader('./components/book/BookList.vue'));

  const vm = new Vue({
    el: '#app',
    // 注册组件 - 局部注册
    components: {
      'book-list': httpVueLoader('./components/book/BookList.vue')
    }
  });
</script>
</body>
</html>

Metadata

Metadata

Assignees

No one assigned

    Labels

    参考示例程序

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions