从零开始的vue学习笔记(五)

单文件组件

Vue.component 来定义全局组件的缺点:

  • 全局定义 (Global definitions) 强制要求每个 component 中的命名不得重复
  • 字符串模板 (String templates) 缺乏语法高亮,在 HTML 有多行的时候,需要用到丑陋的
  • 不支持 CSS (No CSS support) 意味着当 HTML 和 JavaScript 组件化时,CSS 明显被遗漏
  • 没有构建步骤 (No build step) 限制只能使用 HTML 和 ES5 JavaScript, 而不能使用预处理器,如 Pug (formerly Jade) 和 Babel

所以有了文件扩展名为 .vuesingle-file components(单文件组件),例子:

    <template>
    <input
        type="text"
        class="input"
        :value="value"
        v-on="listeners"
    >
    </template>

    <script>
    export default {
    props: {
        value: {
        type: String,
        default: '',
        }
    },
    computed: {
        listeners () {
        return {
            // Pass all component listeners directly to input
            ...this.$listeners,
            // Override input listener to work with v-model
            input: event => this.$emit('input', event.target.value)
        }
        }
    }
    }
    </script>

    <style lang="scss" scoped>
    @import '../variables.scss';

    .input {
     100%;
    padding: 8px 10px;
    border: 1px solid $vue-blue;
    }
    </style>

每一个单文件的基本组成结构都包含:templatescriptstyle 三个部分。

好处:

  • 完整语法高亮
  • CommonJS 模块
  • 组件作用域的 CSS
  • 可以使用包管理器npm、预处理器Babel、打包工具webpack、脚手架vue-cli
    一个完整的单文件组件示例

Vue CLI

这是vue官方提供的脚手架工具

  • npm install -g @vue/cli or yarn global add @vue/cli
  • vue create my-app
  • cd my-app
  • npm run serve

tips:vscode里安装插件vetur和eslint,*.vue单文件里输入scaffold会提示一键生成templatescriptstyle 三个部分。

基础篇的官方文档基本撸完了,后续的学习将通过《极客时间_vue开发实战》进行

原文地址:https://www.cnblogs.com/huangmengke/p/11662620.html