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>
template
模板: HTML模板,用法就和之前学的一样script
元件主程序: 元件实体比需用export default
的方式输出style
元件样式: 放置CSS样式的地方,要注意样式污染问题同时有a.vue
与b.vue
,a.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做区隔
另外,若希望样式能带到子元件身上的话可以在父层的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>
可以利用其他程序语言转成SFC,像是最常见的template
可以用pug
,script
可以用TypeScript
撰写,只要先装相对应的plugin(https://cli.vuejs.org/core-plugins/),并在lang
上指定使用的语言就可以顺利撰写了!!
<template lang="pug"></template>
<script lang="ts"></script>
<style lang="scss"></style>
<<: DAY15:玉山人工智慧挑战赛-中文手写字辨识(Pytorch 自订义资料集)
前言 在昨日取得的资料仅有当天的资讯,政府有提供下载近三年的资料,更多就需要申请,不过我们这三年已经...
本单元系列介绍的《区块编辑器》,正正就是要取代《传统编辑器》而设的新工具,但这个区块可以让你暂时相...
NSIS (Nullsoft Scriptable Install System) 是一个建立安装...
使用 atlantis 做 terraform automation,Terraform Remot...
承接昨天的部分 先使用 create-react-app 将原本的静态页面置换掉 $ npx cre...