组件系统
Vue 组件基础
这里有一个
// 定义一个名为 button-counter 的新组件
Vue.component("button-counter", {
data: function () {
return {
count: 0,
};
},
template:
'<button v-on:click="count++">You clicked me {{ count }} times.</button>',
});
组件是可复用的
<div id="components-demo">
<button-counter></button-counter>
</div>
new Vue({ el: "#components-demo" });
因为组件是可复用的
组件的复用
你可以将组件进行任意次数的复用:
<div id="components-demo">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
注意当点击按钮时,每个组件都会各自独立维护它的
data: {
count: 0;
}
取而代之的是,一个组件的
data: function () {
return {
count: 0
}
}
如果
单文件组件
在很多
- 全局定义
(Global definitions) 强制要求每个 component 中的命名不得重复 - 字符串模板
(String templates) 缺乏语法高亮,在 HTML 有多行的时候,需要用到丑陋的\
- 不支持
CSS (No CSS support) 意味着当 HTML 和JavaScript 组件化时,CSS 明显被遗漏 - 没有构建步骤
(No build step) 限制只能使用 HTML 和ES5 JavaScript ,而不能使用预处理器,如Pug (formerly Jade) 和Babel
文件扩展名为
<template>
<div id="app">
<h1>My Todo App!</h1>
<TodoList />
</div>
</template>
<script>
import TodoList from "./components/TodoList.vue";
export default {
components: {
TodoList,
},
};
</script>
<style lang="scss">
@import "./variables.scss";
*,
*::before,
*::after {
box-sizing: border-box;
}
#app {
max-width: 400px;
margin: 0 auto;
line-height: 1.4;
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: $vue-blue;
}
h1 {
text-align: center;
}
</style>
一个重要的事情值得注意,关注点分离不等于文件类型分离。在现代
<!-- my-component.vue -->
<template>
<div>This will be pre-compiled</div>
</template>
<script src="./my-component.js"></script>
<style src="./my-component.css"></style>