Vue3仿卖座电影开发纪实(三):MVC

476 阅读2分钟

@样式处理

安装sass

cd mymovie

# 在开发环境中安装sass
npm i -D sass

在组件内使用sass的分支语法scss作为组件的样式编辑语言

<!-- 
组件的样式 
lang="scss" 使用scss语法编辑样式
scoped 加作用域(当前组件内定义的样式只作用于当前组件而不会下穿到子组件)
-->
<style lang="scss" scoped>
.tabwrapper {
  display: flex;
  border-bottom: 1px solid #eee;

  .tab {
    flex-grow: 1;
    height: 49px;
    line-height: 49px;
    text-align: center;
  }
}

设置必要的全局样式

src/assets/base.css

* {
  margin: 0;
  padding: 0;

  /* 所有文字取消默认的下划线 */
  text-decoration: none;

  /* width/height包含padding与border */
  box-sizing: border-box;

  /* 全局文字颜色 */
  color: #666;
}

ul,ol,li {
  list-style: none;
}

@配置嵌套路由

配置目标:

  • /film/nowPlaying时,在FilmView中加载NowPlaying子组件
  • /film/comingSoon时,在FilmView中加载ComingSoon子组件

配置路由表

src/router/index.js

  routes: [
    /* 定义路由 */
    {
      /* 父级路由 */
      path: "/film",
      name: "film",
      component: FilmView,

      children: [
        {
          // 当 /film/nowPlaying 匹配成功
          // NowPlaying 将被渲染到 FilmView 的 <router-view> 内部
          path: "nowPlaying",
          component: NowPlaying,
        },
        {
          // 当 /film/comingSoon 匹配成功
          // ComingSoon 将被渲染到 FilmView 的 <router-view> 内部
          path: "comingSoon",
          component: ComingSoon,
        },
      ],
    },
    ...
]

在父组件中配置跳转链接与子组件承载容器

src/views/FilmView.vue

<!-- 组件的模板/DOM -->
<template>
  <div class="tabwrapper">

    <!-- 当路由为/film/nowPlaying时 会加载子组件NowPlaying到当前组件的RouterView中 -->
    <RouterLink active-class="active" class="tab" to="/film/nowPlaying">
      <span>正在热映</span>
    </RouterLink>

    <!-- 当路由为/film/comingSoon时 会加载子组件ComingSoon到当前组件的RouterView中 -->
    <RouterLink active-class="active" class="tab" to="/film/comingSoon">
      <span>即将上映</span>
    </RouterLink>
  </div>

  <!-- 目标组件的承载容器 -->
  <RouterView />
</template>

@加载网络数据

在组件挂载时立即获取数据

src/components/NowPlaying.vue

import { getPlayings } from "../../api/movieApi";
  • 在组件挂载完毕时(mounted生命周期)立即获取数据,并将数据同步给组件实例

src/components/NowPlaying.vue

/* 对外导出组件实例 */
export default {

  /* 组件数据闭包 */
  data() {
    return {
      // 要展示的电影数据
      films: null,
    };
  },

  /* 在组件被挂载时获取数据 */
  mounted() {
    // getPlayings的返回值是Promise对象
    getPlayings(1).then(
      // 拿到Promise履约电影列表数据 赋值给当前组件实例this的films
      (films) => (this.films = films)
    );
  },
  
};

在模板中使用条件渲染

  • 如果数据还未获取到,则显式Loading...
  • 当数据获取完毕时,显式数据内容

src/components/NowPlaying.vue

<template>
  <div>
    <!-- 当电影数据未加载完毕时显式Loading... -->
    <p v-if="films === null" class="loading" >Loading...</p>

    <!-- films加载完毕时显式具体数据 -->
    <p v-else>films: {{ films }}</p>
  </div>
</template>

@渲染热映列表

模板与样式请参考 源码地址