Home Web Front-end JS Tutorial Vuejs single file component (detailed tutorial)

Vuejs single file component (detailed tutorial)

Jun 06, 2018 pm 05:02 PM
vue.js single file component components

This article mainly introduces the detailed explanation of Vuejs single-file component examples. Friends who need it can refer to it

In the previous examples, we defined the components through Vue.component or components attributes. This method is fine in many small and medium-sized projects, but in complex projects, the following shortcomings are very obvious:

String template: lack of highlighting, troublesome to write, especially multi-line HTML Although the template can be written in an html file, it is too intrusive and is not conducive to component decoupling and separation.

No CSS support: means that when HTML and JavaScript are componentized, CSS is obviously omitted

No build step: limited to using HTML and ES5 JavaScript, not preprocessors .

The single-file component with the .vue extension provided by Vuejs provides solutions to all the above problems.

First introduction to single-file components

It is better to use the source code in the tool and create it in the src directory hello.vue file, the content is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<template>

 <h2>{{ msg }}</h2>

</template>

<script>

export default {

data () {

return {

msg:'Hello Vue.js 单文件组件~'

}

}

}

</script>

<style>

h2 {

color: green;

}

</style>

Copy after login

Then introduce and use it in app.js:

1

2

3

4

5

6

7

8

9

10

// ES6 引入模块语法

import Vue from 'vue';

import hello from './hello.vue';

new Vue({

 el: "#app",

 template: '<hello/>',

 components: {

  hello

 }

});

Copy after login

The project cannot be run at this time, because the .vue file webpack cannot be used elsewhere. Yes, it requires the corresponding vue-loader to process it, and careful friends will find that ES6 syntax is used in hello.vue. At this time, you need to use the corresponding syntax conversion loader to convert ES6 into ES5 compatible with mainstream browsers. Syntax, here you need to use the officially recommended babel tool. Install the required loader first:

1

2

# hello.vue 文件中使用了 css,所以需要 css-loader 来处理,vue-loader 会自动调用

npm install vue-loader css-loader babel-loader babel-core babel-preset-env --save-dev

Copy after login

Some people wonder why they need to install so many tools after just using babel-loader . This is because many tools are independent, and loader is just In order to cooperate with the bridge used by webpack, here babel-core and babel-preset-env are the core of implementing ES6 to ES5.

We will modify the webpack.config.js configuration as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

module.exports = {

 // ...

 module: {

  // 这里用来配置处理不同后缀文件所使用的loader

  rules: [

   {

    test: /.vue$/,

    loader: 'vue-loader'

   },

   {

    test: /.js$/,

    loader: 'babel-loader'

   }

  ]

 }

}

Copy after login

For babel configuration, we also need to create a .babelrc file in the project root directory to configure Babel presets and other related plug-ins. , the content is as follows:

1

2

3

{

 "presets": [ "env" ]

}

Copy after login

However, although everything is configured, the project will still report an error, and the following error will be reported:

1

2

ERROR in ./src/hello.vue

Module build failed: Error: Cannot find module 'vue-template-compiler'

Copy after login

Some people are not happy, obviously they installed the dependencies according to the official prompts , and configure it correctly, why does it still report an error? Don't be afraid when you encounter an error. Read what the error is first. It is easy to find that it is because Cannot find module 'vue-template-compiler'. This is because vue-loader also processes .vue files. Need to rely on the vue-template-compiler tool for processing.

At first I didn’t know why the official didn’t directly tell users that they need to install this dependency. After reading vue-loader, I realized that the package.json file contains vue-template-compiler and css-loader As peerDependencies, peerDependencies will not be installed automatically (npm@3.0) during installation, and will only give relevant warnings, so this requires us to install it manually, of course in the .vue file If you need to write CSS, you must also use css-loader, which is also in peerDependencies. Related discussions: https://github.com/vuejs/vue-loader/issues/1158

Now that I know the problem, just install it directly:

1

npm install vue-template-compiler css-loader --save-dev

Copy after login

Run the project again, on the page Our content appears, no error is reported, ok, you’re done~

Using preprocessor

We have learned to write in .vue css, what if you use the sass preprocessor? First install the modules mentioned in the previous article:

1

npm install sass-loader node-sass --save-dev

Copy after login

Configuration only takes two steps:

Modify the vue-loader configuration in webpack.config.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

module.exports = {

 // ...

 module: {

  // 这里用来配置处理不同后缀文件所使用的loader

  rules: [

   {

    test: /.vue$/,

    loader: 'vue-loader',

    options: {

     loaders: {

      // 这里也可以使用连写方式,但是不利于自定义话参数配置

      // scss: 'vue-style-loader!css-loader!sass-loader'

      scss: [

       {

        loader: 'vue-style-loader'

       },

       {

        loader: 'css-loader'

       },

       {

        loader: 'sass-loader'

       }

      ]

     }

    }

   },

   // ...

  ]

 }

}

Copy after login

. To the style tag in the vue file, add the lang="scss" attribute.

After the configuration is completed, you can happily write sass syntax in the .vue file.

Load global settings file

In actual development, when we write sass files, we often extract the global scss variables and put them into a separate file, but this way there is The problem is that every component that needs to be used needs to be manually @import './styles/_var.scss' , which is very unfriendly. The plug-in sass-resources-loader can help us solve this problem very well. Install it first:

1

npm install sass-resources-loader --save-dev

Copy after login

Then modify the vue-loader related configuration in the webpack.config.js file:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

// ...

{

 test: /.vue$/,

 loader: 'vue-loader',

 options: {

  loaders: {

   scss: [

    {

     loader: 'vue-style-loader'

    },

    {

     loader: 'css-loader'

    },

    {

     loader: 'sass-loader'

    },

    // 看这里,看这里,看这里

    {

     loader: 'sass-resources-loader',

     options: {

      // 这里的resources 属性是个数组,可以放多个想全局引用的文件

      resources: [resolve('./src/styles/_var.scss')]

     }

    }

   ]

  }

 }

}

// ...

Copy after login

The configuration is complete, let’s test it again.

Create hello1.vue and hello2.vue files respectively in the src directory:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<!-- hello1.vue -->

<template>

 <h1>{{ msg }}</h1>

</template>

<script>

export default {

name:'hello1',

data () {

return {

msg:'Hello Vue.js 单文件组件~'

}

}

}

</script>

<stylelang="scss">

h1 {

color: $green;

}

</style>

 

<!-- hello2.vue -->

<template>

 <h1>{{ msg }}</h1>

</template>

<script>

export default {

name:'hello2',

data () {

return {

msg:'Hello Vue.js 单文件组件~'

}

}

}

</script>

<stylelang="scss">

h1 {

color: $red;

}

</style>

Copy after login

Then create a styles directory and create a new file _var.scss to store global variables in it:

1

2

$green: rgb(41, 209, 41);

$red: rgb(177, 28, 28);

Copy after login

Next, reference the two components in app.js:

1

2

3

4

5

6

7

8

9

10

11

import Vue from 'vue';

import hello1 from './hello1.vue';

import hello2 from './hello2.vue';

new Vue({

 el: "#app",

 template: '<p><hello1/><hello2/></p>',

 components: {

  hello1,

  hello2

 }

});

Copy after login

Just re-run the project.

Scope style

The single file component provides us with a very convenient function, which is to add the scoped attribute to the style tag , the styles within the tag will only apply to elements in the current component.

接着上面的例子,运行后会发现 hello1.vue 中的 h1 颜色并不是想要的 $green 色,而是被 hello2.vue 中的样式覆盖了。于是分别在 hello1.vue 和 hello2.vue 的 style 标签上添加 scoped 属性,如下:

1

2

3

4

5

6

7

8

9

10

11

12

<!-- hello1.vue -->

<stylelang="scss"scoped>

h1 {

color: $green;

}

</style>

<!-- hello2.vue -->

<stylelang="scss"scoped>

h1 {

color: $red;

}

</style>

Copy after login

这样一来我们的两个 h1 标签颜色都显示正常了。

自定义块

在编写某些开源组件时,有时候我们需要同时维护多个组件和组件说明,但是每次修改就要同时修改 .vue 和 .md 文件,相当麻烦。 .vue 文件的 自定义语言块 功能,就允许我们将 markdown 说明同时写进 .vue 文件中,然后通过插件将其说明部分单独提取到相应的 .md 文件中,这样就可以同时维护说明文档和组件功能了。

比如我们将 hello1.vue 文件修改如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<docs>

 # 标题

  这是标题内容,[仓库地址](https://github.com/yugasun/You-Dont-Know-Vuejs)

 ## 子标题

  这是子标题内容

</docs>

<template>

 <h1>{{ msg }}</h1>

</template>

<script>

export default {

name:'hello1',

data () {

return {

msg:'Hello Vue.js 单文件组件~'

}

}

}

</script>

<stylelang="scss"scoped>

h1 {

color: $green;

}

</style>

Copy after login

然后修改 webpack.config.js 配置:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

const path = require('path');

// 引入相关插件

const ExtractTextPlugin = require('extract-text-webpack-plugin');

function resolve(dir){

 return path.resolve(__dirname, dir);

}

module.exports = {

 // 入口文件

 entry: './src/app.js',

 // 编译输出文件

 output: {

  path: resolve('./'),

  filename: 'build.js'

 },

 resolve: {

  alias: {

   // 因为我们这里用的是 require 引入方式,所以应该使用vue.common.js/vue.js/vue.min.js

   'vue$': 'vue/dist/vue.common.js'

  }

 },

 devServer: {

  // 这里定义 webpack-dev-server 开启的web服务的根目录

  contentBase: resolve('./')

 },

 module: {

  // 这里用来配置处理不同后缀文件所使用的loader

  rules: [

   {

    test: /.vue$/,

    loader: 'vue-loader',

    options: {

     loaders: {

      scss: [

       {

        loader: 'vue-style-loader'

       },

       {

        loader: 'css-loader'

       },

       {

        loader: 'sass-loader'

       },

       {

        loader: 'sass-resources-loader',

        options: {

         resources: [resolve('./src/styles/_var.scss')]

        }

       }

      ],

      docs: ExtractTextPlugin.extract('raw-loader')

     }

    }

   },

   {

    test: /.js$/,

    loader: 'babel-loader'

   }

  ]

 },

 plugins: [

  new ExtractTextPlugin('docs.md')

 ]

}

Copy after login

这里用到了 extract-text-webpack-plugin 导出 text 插件,和 raw-loader ,分别都安装下就行。

然后运行构建命令 npm run build ,等运行结束,根目录下会同时生成一个 docs.md 文件,这就是我们想编写的说明文档。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

集成vue到jquery/bootstrap项目方法?

在vue.js中实现分页中单击页码更换页面内容

在vue2.0组件中如何实现传值、通信

The above is the detailed content of Vuejs single file component (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install the Windows 10 old version component DirectPlay How to install the Windows 10 old version component DirectPlay Dec 28, 2023 pm 03:43 PM

How to install the Windows 10 old version component DirectPlay

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Explore how to write unit tests in Vue3

VUE3 development basics: using extends to inherit components VUE3 development basics: using extends to inherit components Jun 16, 2023 am 08:58 AM

VUE3 development basics: using extends to inherit components

Detailed example of vue3 realizing the typewriter effect of chatgpt Detailed example of vue3 realizing the typewriter effect of chatgpt Apr 18, 2023 pm 03:40 PM

Detailed example of vue3 realizing the typewriter effect of chatgpt

A brief analysis of how vue implements file slicing upload A brief analysis of how vue implements file slicing upload Mar 24, 2023 pm 07:40 PM

A brief analysis of how vue implements file slicing upload

How to implement calendar component using Vue? How to implement calendar component using Vue? Jun 25, 2023 pm 01:28 PM

How to implement calendar component using Vue?

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) Mar 23, 2023 pm 07:53 PM

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages)

See all articles