Day15-Vue SFC 单一元件档

SFC是什麽

Single-file components单一元件档是一个集合HTML、JavaScript 及 CSS的档案,用.vue档案作为一个元件。

从建置好的Vue CLI中打开App.vue可以看到它是由三部分组成

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js App"/>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
  1. template模板: HTML模板,用法就和之前学的一样
  2. script元件主程序: 元件实体比需用export default的方式输出
  3. style元件样式: 放置CSS样式的地方,要注意样式污染问题

同时有a.vueb.vuea.vue的红色样式也会染到b.vue身上

a.vue

<template>
  <h1>This Component A!</h1>
</template>

<style>
h1 {
  color: red;
}
</style>
b.vue

<template>
  <h1>This Component A!</h1>
</template>
App.vue
<template>
  <component-a />
  <component-b />
</template>

<script>
import componentA from "./components/a.vue";
import componentB from "./components/b.vue";

export default {
  name: "App",
  components: {
    componentA,
    componentB,
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

为了解决这个问题,可以用scoped做到区隔,b.vue的字就会变回原本的黑色

a.vue

<template>
  <h1>This Component A!</h1>
</template>

<style scoped>
h1 {
  color: red;
}
</style>

检视的时候也可以看到Vue.js是透过随机生成的[data-v-xxxx]来帮两个元件的css做区隔

Untitled

另外,若希望样式能带到子元件身上的话可以在父层的css做改写,使用::v-deep([selector]),如此一来就可以将加了scoped的样式给子元件

<style scoped>
::v-deep(h3) {
  color: red;
}
</style>

外部档案作为来源引入

注意!!!只有style可以引入多个

<template src="./hello.html"></template>

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

<style src="./hello.css"></style>

lang使用其他语言开发

可以利用其他程序语言转成SFC,像是最常见的template可以用pugscript可以用TypeScript撰写,只要先装相对应的plugin(https://cli.vuejs.org/core-plugins/),并在lang上指定使用的语言就可以顺利撰写了!!

<template lang="pug"></template>

<script lang="ts"></script>

<style lang="scss"></style>

<<:  DAY15:玉山人工智慧挑战赛-中文手写字辨识(Pytorch 自订义资料集)

>>:  浅谈MVVM

【D7】取得历史资料:三大法人-区分期货与选择权二类

前言 在昨日取得的资料仅有当天的资讯,政府有提供下载近三年的资料,更多就需要申请,不过我们这三年已经...

11 | WordPress 传统区块 Classic Block

本单元系列介绍的《区块编辑器》,正正就是要取代《传统编辑器》而设的新工具,但这个区块可以让你暂时相...

笔记我使用 NSIS 制作 Windows 安装档的过程

NSIS (Nullsoft Scriptable Install System) 是一个建立安装...

Day 11-Atlantis 做 Terraform Remote Plan & Remote Apply

使用 atlantis 做 terraform automation,Terraform Remot...

Day10-使用 create-react-app 部署第一个 React static Web

承接昨天的部分 先使用 create-react-app 将原本的静态页面置换掉 $ npx cre...