This article shares with you a specific analysis of SFC and vue-loader in Vue. The content is very good. Friends in need can refer to it. I hope it can help everyone.
Official website: https://vue-loader.vuejs.org/zh/
vue-loader is a webpack loader. Simply put, it converts vue files into JS modules. When the babel-loader or bubble-loader configuration is detected, ES2015 is automatically supported;
Using vue-loader, you can write a component in the form of Vue Single-File Component (SFC), that is, a single file component.
.vue Single File Component (SFC) Specification
1. Template block
At most one Its content will be extracted as a string and passed to vue-template-compiler, then webpack will compile it into a js rendering function and finally injected into the component exported from <script>;</script>
2. <script>Script block</script>
One SFC can have at most one <script> block; <br/> Its default export should be a Vue.js component options object, which can also be exported by Vue. The extension object created by extend(). <br/>Thinking: data in Vue.extend() must be a function, so in the script of .vue SFC, the data in export is a function</script>
3.
A .vue file can contain multiple
4. Custom language block
vue-loader will use the block name to find the corresponding loader for processing. You need to configure webpack.config
5. All language blocks Support src import
The import path follows the same path resolution rules as webpack module request
// The relative path needs to start with ../
vue-loader feature overview
Supports the use of other non-default languages for each template, script, and style module of the component, such as:
In addition to the default and other language blocks, you can also add custom blocks, and then use a custom loader to process them
Simulate the local scope for the css in the component and directly declare
Treat the static resources (pictures, etc.) in style and template as modules Dependencies and processed by webpack loader
Hot reloading in development mode
Preprocessing
Vue supports various types of preprocessors, which can compile language blocks. For example, Vue uses PostCSS to process css by default. You can use sass, less, stylus, etc. For the js part, Vue uses babel by default, and you can also use For coffee, typescript, etc., you only need to install the corresponding loader. Vue will infer the corresponding loader based on the lang attribute of the language block and the option rules of the webpack configuration.
Little chestnut: css uses sass preprocessing
$ npm install sass-loader node-sass --save-dev
// webpack.config.js -> module.rules { test: /\.sass$/, use: [ 'vue-style-loader', 'css-loader', { loader: 'sass-loader', options: { indentedSyntax: true //sass-loader 默认解析 SCSS 语言 } } ] }
<!-- .vue -> style 增加lang属性并赋值 --> <style> /* write SASS here */ </style>
The template is handled slightly differently, because most Webpack template processors (such as pug-loader) will return the template To handle functions, instead of compiled HTML strings, we can replace pug-loader with raw pug.
<!-- .vue -> template --> <template> p h1 Hello world! </template>
CSS scope: scope
When the
<style> /* global styles */ </style> <style> /* local styles */ .example { color: red; } </style> <template> <p>hi</p> </template>
The CSS output processed by vue-loader is scope rewritten through PostCSS. After PostCSS processing, it is as follows:
<style> .example[data-v-f3f3eg9] { color: red; } </style> <template> <p>hi</p> </template>
When using scope, the root node of the child component will be affected by the parent component scope CSS
When using scope, the style of the parent component Does not leak into child components. But the root node of the child component will be affected by the parent scope CSS and the child scope CSS. This is so that the parent can style the root element of the child component for layout.
Enable the parent component to use the ' >>> ' or ' /deep/ ' depth selector to act on the child component
<style> .a >>> .b { /* ... */ } </style>
compiles to
.a[data-v-f3f3eg9] .b { /* ... */ }
动态生成的DOM内容不受scope style的影响,但可以使用深度选择器进行样式改变
使用scope作用域不能弃用class或id等
考虑到浏览器渲染各种 CSS 选择器的方式,当使用 scoped 时,选择属性选择器如p { color: red } 在作用域中会慢很多倍(即当与属性选择器组合时)。如果你使用 class或者 id 代替,比如 .example { color: red },这样几乎没有性能影响
在递归组件中注意后代选择器
对于带有.a .b的CSS选择器,如果匹配.a的元素包含递归子组件,则该子组件中的所有.b将与其匹配。
小思考:在template中只包含一个外层节点,不能多个节点并列,这个设计思路遵循父组件可以操作子节点的一个根节点,即使在CSS局部作用域下依然有效
CSS模块模式:module
一个CSS Module其实就是一个CSS类型的文件,其编写方式与CSS相同,但在编译时会编译为ICSS低级交换格式。
其默认所有的类名/动画名都在本地作用域,当从JS模块导入CSS模块时,它会导出包含从本地名称到全局名称的所有映射的一个对象
在CSS Module中,所有的url和@import都是被看成模块依赖,例如url(./image.png) 会被转换为 require(‘./image.png’)
CSS 模块处理是通过 css-loader,请求的资源可以是在node_modules中。
Vue loader中的CSS Module
配置
Vue loader集成了CSS Module,使用前需要在css-loader中设置modules: true,如下:
// webpack.config.js -> module.rules { test: /\.css$/, use :[ 'vue-style-loader', { loader: 'css-loader', options: { // enable CSS Modules modules: true, // customize generated class names localIdentName: '[local]_[hash:base64:8]' } } ] }
然后就在
<style> .red { color: red; } </style>
使用
这样Vue loader会将css module本地对象编译为计算属性注入到组件中,默认值为$style。template可以通过动态类绑定使用:
<template> <p> This should be red </p> </template>
JS也可以通过this.$style访问:
<script> export default { created () { console.log(this.$style.red) // -> "red_1VyoJ-uZ" // an identifier generated based on filename and className. } } </script>
为多个style自定义标识符
一个.vue组件可以有多个
<style> /* 标识符注入为 a */ </style> <style> /* 注入为 b */ </style>
结合预处理
CSS Module还可以在预处理(SASS,LESS等)中使用,在配置webpack rules时加上modules: true,例如:
// webpack.config.js -> module.rules test: /\.scss$/ use[{ loader: 'css-loader', options: { modules: true } }]
.vue中自定义节点/语言块
除了默认的等节点,还可以加自定义节点,并使用自定义的loader处理他们;
可以给节点加lang属性,此时节点rule匹配lang的扩展;
如果没有标记lang,则自定义节点的name和rule需要在webpack中声明。
小栗子:自定义语言块
首先需要loader。为了将自定义块注入到组件中,自定义一个loader如下:
// myblock-loader.js module.exports = function (source, map) { this.callback( null, `export default function (Component) { Component.options.__myblock = ${ JSON.stringify(source) } }`, map ) }
配置到webpack
// webpack.config.js -> module.rules { resourceQuery: /blockType=myblock/, loader: require.resolve('./myblock-loader.js') }
在组件中使用
<!-- ComponentB.vue --> <template> <p>Hello</p> </template> <myblock> This is the documentation for component B. </myblock>
组件间的复用
<!-- ComponentA.vue --> <template> <p> <componentb></componentb> </p> <p>{{ myblock }}</p> </template> <script> import ComponentB from './ComponentB.vue'; export default { components: { ComponentB }, data () { return { myblock: ComponentB.__myblock } } } </script>
热重载:不刷新页面的更新
当更改.vue的template或style时,页面不刷新也可实现内容动态的变化,并保留着程序及其组件的状态。在以下情况下会保持热重载:
编辑组件的
编辑组件的,实例会重现,这是因为被编译成新的渲染函数,不会产生副作用。
编辑组件的部分<script>,编辑的实例将销毁后重建,这是因为<script>可能包含产生副作用的生命周期钩子,因此需要“重新加载”以确保一致的行为。如果组件产生全局副作用则需要整页的重新加载。</script>
热加载是默认启动的,当以下情况下关闭:
webpack target is node (SSR)
webpack压缩代码
生产模式:process.env.NODE_ENV === 'production'
也可以手动禁用热重载:
// webpack.config.js -> module.rules { test: /\.vue$/, loader: 'vue-loader', options: { hotReload: false // disables Hot Reload } }
功能组件
一个简单的.vue组件可以声明为无状态的(没有反应数据)和无实例的(没有此上下文)的功能组件。
vue.js 2.5版本以上,在template中加上functional属性即可声明:
<template> </template>
在script中的结构为:
Vue.component('my-component', { functional: true, props: { //也可不定义props // ... }, render: function (createElement, context) { // createElement, context 为上下文参数 // ... } })
组件加上functional: true后,更新渲染函数需要添加context参数,故this.$slots.default更新为context.children,this.level更新为context.props.level。
功能组件通过context对象传递/获取所有的内容,例如:
context.props: 包含功能组件的props的对象,在vue 2.3+如未定义的props属性会自动加到组件根元素上;
context.children: 包含VNode子节点的数组
context.slots: 返回slots对象的函数
context.data: 整个数据对象,作为createElement的第二个参数传递给组件
context.parent: 指向父组件
context.listeners: (2.3.0+) data.on的别名,包含父级注册事件侦听器的对象。
context.injections: (2.3.0+) 包含组件的注入项
由于功能组件只是功能,缺少持久化实例,因此渲染的成本要低得多,也不会出现在Vue devtools组件树中;
适用于作为封装组件封装子节点/props/data后传递给子组件;
功能组件也支持预处理/scope/热重载等。
静态资源url是如何处理的
webpack配置module.exports需要vue-loader,同时也会有各种静态资源的loader。当Vue Loader编译SFC中的时,将会把所有关联的静态资源url转为webpack module请求。例如:
<img src="/static/imghwm/default1.png" data-src="../image.png" class="lazy" alt="Detailed analysis of SFC and vue-loader in Vue" >
会编译为:
createElement('img', { attrs: { src: require('../image.png') // this is now a module request } })
URL路径解析规则:
绝对路径原样保存;
以“.”开头,则将其解释为相对模块请求,并根据文件系统上的文件夹结构解析;
以“~”开头,则将其后的内容解析为模块请求,可以在节点模块引用这些内容;
以“@”开头,则其后的内容也被解释为模块请求,@在vue-cli创建的项目中默认指向/ src,可以使用webpack配置@别名
相关推荐:
The above is the detailed content of Detailed analysis of SFC and vue-loader in Vue. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software