This article ensures that the problem only increases, so that the radius of knowledge continues to lengthen
What if WebPack packages vUE too slowly?
- Configuration externals
- The ParallelUglifyPlugin replaces the built-in UglifyJsPlugin plug-in for code compression
- Plug-in libraries that do not need to be packaged and compiled are global
<script>
The way the tag is introduced - Using the CommonsChunkPlugin to extract common modules reduces file size and also helps with file caching at the browser level
/ / to extract the public module file new webpack.optimize.Com monsChunkPlugin ({chunks: Hash filename: '[name].js' + (isProduction? '? [chunkhash:8]' : "), name: 'common'}), // If you want to use the common module, you will need to specify the default module to put in the public file. Common: ['jquery', 'react', 'react-dom']}, './ SRC /js/detail', '.Copy the code
- Use HappyPack to speed up the build
HappyPack will use multiple processes to package and build it. It is easy to use, but it does not allow all Loaders to be introduced first
HappyPack = require('happypack'),
os = require('os'),
happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });
Copy the code
Then change the module rule and introduce it, where ID is an identifier
{ test: /\.jsx? Es6: /node_modules/, loader: 'HappyPack/loader? id=js' // use: [{ // loader: 'babel-loader', // options: { // } // }] }Copy the code
We then call the plug-in, set the matching ID, and the relevant configuration can be applied directly to the use: rule part on loaders
new HappyPack({
id: 'js',
loaders: [{
loader: 'babel-loader',
options: {
// cacheDirectory: true
}
}]
}),
Copy the code
The first thing to note is that it has poor support for file-Loader and URl-loader, so there is no need to replace these two loaders with happypack, and other loaders can do the same
The second thing to note is that extracting CSS files using the ExtractTextWebpackPlugin is not completely convertible, so it requires a small change, such as
Module: {rules: [{test: /\.css$/, // loader: 'HappyPack/loader? Id = CSS 'use: CssExtractor. Extract ({// if configured not to extract, insert this file into the <head> tag using a styleloader fallback: 'styleloader ', use: 'HappyPack/loader?id=css' // use: [{ // loader: 'css-loader', // options: { // // url: false, // minimize: true // } // }, // // 'postcss-loader' // ] }) }, { test: /\.scss$/, // loader: 'HappyPack/loader? Id = SCSS ' SassExtractor. Extract ({// if configured not to extract, insert this file into the <head> tag using a style-loader fallback: 'style-loader', use: 'HappyPack/loader?id=scss' // use: [ // 'css-loader', // // 'postcss-loader', // { // loader: 'sass-loader', // options: { // sourceMap: true, // outputStyle: 'compressed' // } // } // ] }) }Copy the code
Since it is a direct function call, we just put the use rule in the inner layer and then configure the plug-in
plugins: [
new HappyPack({
id: 'css',
loaders: [{
loader: 'css-loader',
options: {
// url: false,
minimize: true
}
}]
}),
new HappyPack({
id: 'scss',
loaders: [{
'loader': 'css-loader'
}, {
loader: 'fast-sass-loader',
options: {
sourceMap: true,
outputStyle: 'compressed'
}
}]
}),
Copy the code
- Some plug-ins are introduced as modularity, which mainly introduces useful code
Import {debounce} from 'lodash'; // Import debounce from 'lodash/debounce';Copy the code
- Use asynchronous module loading
Ensure is used to set which modules need to be loaded asynchronously. Webpack packs it into a separate chunk.
At some point (such as when the user clicks view) the module is loaded asynchronously for execution
$('.bg-input').click(() => {
console.log('clicked, loading async.js')
require.ensure([], require => {
require('./components/async2').log();
require('./components/async1').log();
console.log('loading async.js done');
});
});
Copy the code
- Sometimes you don’t need to resolve dependencies on modules that don’t have dependencies or are not modularized at all,
With noParse, you skip parsing directly
module: {
noParse: /node_modules\/(jquey\.js)/
}
Copy the code
- Optimize search paths at build time
When webPack is packaged, there are various paths to query for searches, and we can add some configuration to make it search faster
For example, a module path that is easy to change to an absolute path can be changed, and a pure module name can be introduced with some directory paths
You can also be adept at using the resolve Alias alias field
There are also configurations such as exclude, to avoid unnecessary searching files, such as Babel, don’t forget to exclude the files that don’t need to be traversed
{ test: /\.jsx? // use: [{loader: 'babel-loader', options: {}}]} // use: [{loader: 'babel-loader', options: {}}]}Copy the code
- Take a look at the modules involved in the packaging build and see which packages you don’t need to pack, but only the modules you need to pack
When compiling webPack, you can add the json > stat.json parameter to your analysis site, such as Webpack-analyse or Webpack-Visualizer, to see the information of the packed modules
- Extract common code
How to solve the problem of vUE packaging Vendor being too large?
-
Reduce the size of the common package: Vendor packages are too large because the js that references the third party plug-in is too large. You can directly reference the image in the index script to solve the problem.
-
Template packages should not be too large: Vue-Router is imported on demand, which unpacks
Vue home page white screen is what problem caused? How to solve it?
Home page white screen problem:
The home page is slow to load because it is a single-page application that requires all required resources to be downloaded to the browser and parsed. So the bigger the page, the longer it takes to load, and the longer it takes to execute the JS, the later the DCL happens, so the white screen
The solution:
- Optimized WebPack to reduce module packaging volume, code-split load on demand
- Server side rendering, in the server side pre-assembled the HTML required for the home page
- Loading or skeleton screen on home page (just to optimize the experience)
- Enable GZIP compression on the server
- Package file subcontract, extract the public file package
How to optimize the loading speed of the home page?
- Browser cache
- Gzip compression
- Content Delivery Network (CDN)
- Asynchronous script
<script async src=""></script>
Copy the code
- Reduce file size by optimizing your JavaScript, HTML, and CSS code to remove all unnecessary whitespace and comments
- Delayed parsing of JavaScript, by delaying the parsing of scripts, can reduce the initial site load time
- To enable the Keep Alive
- Do not use inline CSS
- Avoid blocking JavaScript and CSS
Delay loading unimportant JavaScript, or load it asynchronously. Another option is to embed this HTML code into the site, and you need to make sure your CSS is optimized.
- Image and file formats
It is recommended to use JPEG rather than GIF and PNG images unless the image contains an Alpha factor or is transparent.
- File separation
The site’s files can be divided into CSS, JavaScripts, and images. File separation does not directly improve your site’s load time. However, doing so can improve server stability, especially when there are sudden spikes in web traffic. Subdomains can also be used to host files, which can increase the number of parallel downloads.
- Minimize HTTP requests
When a site receives too many HTTP requests at once, its visitors experience delayed response times, which increases both CPU usage and page load times. So how do you reduce HTTP requests? See the following steps.
- Reduce the number of objects on your site.
- Minimize the number of redirects on your site.
- Use CSS Sprites (just the part of the image you need).
- Combine JavaScripts and CSS.
Analyze the reason why the Vue project reported 404 after the local development was completed and deployed to the server.
-
Check the NGINx configuration to see if the resource mapping conditions are correctly set
-
Check whether publicPath is configured in vue.config.js. If yes, check whether it is in the same location as the project resource file on the server
What preparations should be made before the VUE deployment goes online?
- Check whether the configuration environment is correct
- The git version is correct
- Whether the packing road strength is correct
- Ngnix configuration
- Remove the console
What are the Vue development specifications?
-
mandatory
- Component names are multiple words
export default { name: 'TodoItem', // ... } export default {name: 'Todo', //... }Copy the code
- The data of a component must be a function
- Prop definition should be as detailed as possible, including type, default value, required or not, and validate
- Set the key for for
- Avoid using v-if and V-FOR together
- Set scope for the component style
- Use full words
-
advice
- Using component files
components/TodoItem.vue Copy the code
- Abbreviated instructions
-
Use with caution (potentially dangerous mode)
- Scoped uses element selectors
- Communication between parent and child components via prop and events is preferred over this.$parent or changing prop
- No key used in v-if/ V-if-else/V-else
If a set of v-if + V-else elements are of the same type, it is best to use a key
How do I access the child component’s data when a slot is used in the parent component
<template> <div> <h2> Default slot </h2> <slot :toParent="childrenData" :toParent2="childrenData2"> {{childrendata.data1}} {{childrendata2.data1}} </slot> <h2> <slot name="header" :headerData="headerData"> {{headerData.data1}} </slot> </div> </template> <script> export default{data(){return{childrenData:{data1:' childrenData ', data2:' childrenData ',}, ChildrenData2 :{data1:' childrenData2: ', data2:' childrenData2: ',}, headerData:{data1:' childrenData2: ', 'childrenData2: ',},},} </script>Copy the code
SlotProps is a collection of arbitrarily named slot prop. At this point the value of slotProps. ToParent is the value of childrenData
The parent component <template> <div> <myComponent> // slotProps and headerProps represent a collection of slot prop, Its name can literally take < template v - slot: default = "slotProps" > {{slotProps. ToParent. Data2}} {{slotProps. ToParent2. Data2}} < / template > < template v - slot: header = "headerProps" > {{headerProps. HeaderData. Data2}} < / template > / / when a child components have more than one slot prop on slot, <template v-slot:default="{toParent,toParent2}"> {{toparent. data2}} {{toparent2.data2}} </template> <template v-slot:header="{headerData}"> {{headerData.data2}} </template> // You can also rename the value bound to the child component slot <template #default="{toParent:a,toParent2:b}"> {{a.data2}} {{b.data2}} </template> <template #header="{headerData:c}"> {{c.data2}} </template> </myComponent> </div> </template>Copy the code
DOM options el, Template, render
- El:
Provide a DOM element that already exists on the page as the mount target for the Vue instance
. It can be a CSS selector or an HTMLElement instance.- Because all mount elements are replaced by Vue generated DOM. Therefore, it is not recommended to mount Vue instances to HTML or body.
- If this option exists in const VM = new Vue({}), the instance will immediately go through the compilation process; otherwise, manually start the compilation process by explicitly calling vm.$mount().
El exists in vm = new Vue({})
<script>
const vm= new Vue({
el:'#app',
data:{
age:17
},
}
</script>
Copy the code
Manually enable compilation by explicitly calling vm.$mount()
<script>
const vm= new Vue({
data:{
age:17
},
})
vm.$mount('#app')
</script>
Copy the code
- Template: a string template
Used as an identifier for the Vue instance
. If the EL exists, the template will replace the mounted elements. The contents of the mounted elements are ignored unless the contents of the template have distribution slots.- If the value starts with #, it is used as a selector and the innerHTML of the matching element is used as a template.
Const vm= new Vue({el:'#app', data:{age:17}, template:'<div> ',}) </script>Copy the code
< span style =" box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 13px! Important; word-break: inherit! Important;" el:'#app', data:{ age:17 }, template:'#mb', }) </script>Copy the code
Template, id and # are combined
< span style =" box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 13px! Important; word-break: inherit! Important;" </template> </body> <script> const vm= new Vue({ el:'#app', data:{ age:17 }, template:'#mb', }) </script>Copy the code
- render :
If the render function in the Vue option is present, the Vue constructor does not compile the render function from the HTML template extracted from the template option or the mount element specified through the EL option
.
<div > <div > <script> const vm= new Vue({el:'#app', data:{age:17}, < span style = "box-sizing: border-box; color: RGB (74, 74, 74); font-size: 14px! Important; white-space: inherit! Important;" ${this.age}}) </script>Copy the code
What are the life cycles (hook functions) of custom directives? How do I write a custom instruction?
- Bind: called only once, when a directive is first bound to an element, and can be initialized in this hook function;
- Inserted: called when the bound element is inserted into the parent, after bind;
- Update: called when the bound component’s VNode is updated, but may occur before its children are updated.
The value of the instruction does not necessarily change when called, and unnecessary template updates are ignored by comparing the values before and after the update;
- ComponentUpdated: directive component VNode and its children VNode all updated call;
- Unbind: called only once, when a directive is unbound from an element.
Vue.directive('color', { bind:function(){ alert('bind') }, inserted: function (el,binding) { alert('inserted') el.style.color=binding.value; }, update:function(el,binding){ alert('update') el.style.color=binding.value; }, componentUpdated:function(el,binding){ alert('componentUpdated') el.style.color=binding.value; }, unbind:function(){alert('v-color ')}})Copy the code
What are the benefits of the render function?
The template will be translated into render, only a little, the template elements in tag_name is static, do not change, use createEelment can generate different tag_name, such as h1… H6, which can be controlled by a number variable
Vue Mounting process
[Vue Principle] $Mounted source analysis
Do you know what high-level components are?
Definition of a high-level component (HOC) that takes a component as an argument and returns a new component
Features of a high-order component (HOC) :
- It should be a pure function with no side effects and should not modify the original component, that is, the original component cannot be changed
- Doesn’t care what data (props) you’re passing, and the newly generated component doesn’t care where the data came from
- The props received should be passed transparently to the wrapped component
Pass the original component prop directly to the packaged component
- You can add, delete, and modify props
Example 1
<template>
<div>
<p @click="Click">props: {{test}}</p>
</div>
</template>
<script>
export default {
name: 'Base',
props: {
test: Number
},
methods: {
Click () {
this.$emit('Base-click')
}
}
}
</script>
Copy the code
Example 2
export default function Console (BaseComponent) {
return {
template: '<wrapped v-on="$listeners" v-bind="$attrs"/>',
components: {
wrapped: BaseComponent
},
mounted () {
console.log('haha')
}
}
}
Copy the code
Have you read about Vue. Observable?
Make an object responsive. Serves as a minimized cross-component state store. It’s kind of like the little Vuex
const store = Vue.observable({name:'hhy'}); Const mutation = {updateName(name){store.name = name}} Store and mutaion can be invoked on computed and Methods, respectivelyCopy the code
How to solve the problem that img SRC does not take effect in Vue?
Because dynamically adding SRC is treated as a static resource and is not compiled, require is added
The Component tag and is special features applied to components
- Dynamic components
<component :is="componentName"></component>
Copy the code
ComponentName can be a local componentName and a global componentName that have been registered on this page, or it can be an option object for a component.
When the control componentName changes, you can dynamically switch the selection of components.
- Is the use of the
Some HTML elements, such as
-
,
-
,
<ul>
<name-list></name-list>
</ul>
Copy the code
The above
<ul>
<li is="nameList"></li>
</ul>
Copy the code
What is the difference between delete and vue. delete?
- Delete: only the members of the deleted object become ‘ ‘or undefined, and the keys of other elements remain unchanged;
- Delete: Deletes an object member directly. If the object is reactive, make sure the deletion triggers an update to the view. This method is primarily used to circumvent the restriction that Vue cannot detect that an attribute has been deleted.
Have you ever used EventBus? Say what you understand
Communication between VUE components is achieved by using an empty VUE instance as a bridge. It is a solution to achieve communication between non-parent and child components.
- Create a vue instance and export it
import Vue from 'Vue'
export default new Vue
Copy the code
- Introduce this bus.js in each of the two components that need to communicate
Import Bus from 'here is the path where you imported bus.js' // Bus is free to change the name it likesCopy the code
- The component passing the data sends the event name and the data to be passed through the VUE instance method $emit. (Send data component)
$emit('click',data) // Emit ('click',data) // Emit ('click',data) // emit('click',data)Copy the code
- The component in which the data is being passed listens for events and receives data through the vUE instance method $on.
$on('click',target => {console.log(target))// You can call it whatever you like (as long as it follows the naming convention of the parameter, of course)})Copy the code
- Clears eventBus with the $off method of the Vue instance in the Vue life cycle beforeDestroy or Destroyed
beforeDestroy(){
bus.$off('click')
}
Copy the code
When an EventBus is registered globally, the event is repeatedly triggered during route switchover. How do I solve this problem?
Use $off in the beforeDestroy hook function in components that use $ON.
How to do SEO optimization for search engines after using Vue?
SEO:
- Website structure: Keep your website structure clear and flat
- Navigation: Pages should have concise navigation. Navigation lets the search engine know the structure of the site, and also lets the search engine know the current page in the hierarchy of the site structure.
- Standard URL: The URL should be as short as possible to minimize the variable parameters contained in dynamic URL.
- Sitemap submission: A Sitemap notifies search engines of what web pages are available on their site so they can crawl smarter.
- Reasonable HTTP return codes: Search engines process different return codes differently
- Appropriate title: Tell the search engine the main content of the page
- The appropriate description
- Semantic HTML
A better project solution for SEO support is to use server-side rendering. So if your project has SEO requirements, then a better solution is server-side rendering.
Why does Vue require component templates to have only one root element?
let vm = new Vue({
el:'#app'
})
<body>
<div id='app1'></div>
<div id='app2'></div>
</body>
Copy the code
Vue doesn’t really know which one is our entry, because for an entry, that entry is a ‘Vue class’, and Vue needs to render, process, and insert everything in that entry back into the DOM.
If multiple entries are set at the same time, vue does not know which is the ‘class’.
Why must there be only one div under template?
The Template tag is a new HTML5 tag that has three features:
1. Hidability: This TAB is never displayed anywhere on the page, even if there is much content in it, it is always hidden.
2. Arbitrariness: The tag can be written anywhere on the page, even inside the head, body, or SciPRt tags.
3. Ineffectiveness: Any HTML content in this tag is invalid and has no effect.
However, you can get the contents of the contents through innerHTML.
In essence, a single file component is essentially treated by various loaders as a.js file (because when you import a single file component and print it out, it’s a vue instance). As we know from the arbitrariness of template, the HTML wrapped in template can be written anywhere. For a.vue, the contents of this template are the contents that vue will render as a virtual DOM, bringing the result back to the beginning: if a.vue single-file component is a Vue instance, where is the entry point to that instance?
If there are multiple divs under template, how do I specify the root entry for this vue instance?
In order for the component to properly generate a vue instance, the div is naturally treated as the entry to the program.
Through this’ root node ‘, we recursively traverse all nodes under the vUE ‘tree’ and process it into vDOM, which is rendered into real HTML and inserted at the correct location
So the entry is the ‘root’ of the tree, and the child elements, the child components, are the ‘branches’ of the tree, and the’ tree ‘is, naturally, an instance of vue.
Do you know how nextTick works?
See my another article: [Vue principle] $nextTick source analysis
What is your understanding of Vue template compilation?
Render function returns VNode (vUE’s virtual DOM node)
- Template strings are parsed by the compile compiler, and labels, instructions, and attributes are compiled into the AST syntax tree (i.e., the tree representation of the abstract syntax structure of the source code). Compile is the return value of the creatCompiler (createCompiler is used to create the compiler). Compile is responsible for merging options
AST:
Node {
type: 'File',
start: 0,
end: 156,
loc:
SourceLocation {
start: Position { line: 1, column: 0 },
end: Position { line: 10, column: 0 } },
errors: [],
program:
Node {
type: 'Program',
start: 0,
end: 156,
loc: SourceLocation { start: [Object], end: [Object] },
sourceType: 'module',
interpreter: null,
body: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
directives: [] },
comments: [] }
Copy the code
- The return value of render is VNode. VNode is Vue’s virtual DOM node. It contains (tag name, child node, text, etc.)
What is a template precompile?
Precompile: Precompile to render during the packaging phase (i.e., during the build of the project)
Because if you can, you can remove the compile part from the vue source code to further reduce the size; You can also improve performance by allowing the actual component to skip template rendering at Runtime
For Vue components, the template of Vue is converted to the render function at runtime. The compilation of the template is compiled only once when the component is instantiated, and the generation of the render function is not compiled again. Therefore, the compilation of the component’s runtime is a performance cost. So think about precompiling.
What is the process of mounting a Vue instance?
Instance mount is primarily an implementation of the $mount method, In SRC/platforms/web/entry – the runtime – with – compiler. Js & SRC/platforms/web/runtime/index. The js file has the Vue. Such as the prototype, the definition of $mount
In $mount approach, will determine the options in the el exists, then render judgment (with the presence of the template also needs to have render function), and then is to determine the template, the template to do a check, Finally, use compileToFunctions to convert the template to Render and staticRenderFns
Why is axios officially recommended instead of Vue-Resource?
- Vue – Resources is no longer updated, vue writer Yu Da recommended Axios.
- Axios is more powerful
- Axios is a web request library that builds on ES6 Promise. It is also a wrapped XMLHttpRequests library.
- Axios builds XHR in the browser, converts or intercepts the request data or response data through nodeJS, supports Promise apis, cancles requests, automatically converts JSON, and defends against XSRF attacks!
- Vue-resources is available in a browser version only
How to encapsulate axios in VUE?
import axios from 'axios' axios.defaults.baseURL = ... axios.defaults.timeout = 10000; axios.defaults.headers.post['Content-Type'] = 'application/json'; / / request intercept axios. Interceptors. Request. Use (config = > {/ / can log in here return config. }, error => { return Promise.reject(error); }); / / response to intercept axios. Interceptors. Response. Use (response = > {/ / if the returned a status code of 200, shows that interface request is successful, If (response.status === 200) {if (response.data.code === 900) {message.error (response.data.msg)} return Promise.resolve(response); } else { return Promise.reject(response); } }, error => { if (error.response && error.response.status === 401) { window.localStorage.removeItem('token'); }}); Function get(url, params, config = {}) {return new Promise((resolve,)) reject) => { axios.get(url, { params, ... config, }).then(res => { resolve(res.data); }).catch(err => { reject(err.data); })}); } function post(url, params, config = {}) { return new Promise((resolve, reject) => { axios.post(url, params, { ... config, }) .then(res => { resolve(res.data); }) .catch(err => { reject(err.data); })}); }Copy the code
Has Vue ever encountered an interruption to an AXIos request while switching pages? How to interrupt?
Scene: in Vue single page in the development process, encountered such a situation, when I switch pages, due to the previous page request execution time is long, switch to the page, is not performed, then the request will continue until the end of the request, the page will influence the performance, and may cause certain influence to now page data show.
So we should interrupt all previous requests before switching pages
- Create a Cancel token using the canceltoken.sourse factory method
const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else {// handle error}}); axios.post('/user/12345', { name: 'new name' }, { cancelToken: Token}) // Cancel the request (the message argument is optional) source.cancel('Operation canceled by the user.');Copy the code
- CancelToke is created by passing an executor function to the CancelToken constructor
const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: New CancelToken(function executor(c) {// cancel = c; })}); // cancel the request cancel();Copy the code
What if you synchronize axiOS asynchronous requests?
Synchronize an AXIos asynchronous request with asyns/await
async getData (params) {
try {
let res = await axios.get('url', {
params
})
this.tableData = res.data.result
} catch (err) {
console.log(err)
}
}
Copy the code
You can also define a new Promise and use it with asyns/await
function getData (data) { return new Promise((resolve, reject) => { axios.get('url', { params: data }).then((res) => { resolve(res) }).catch((err) => { reject(err) }) }) } async function useFun(){ try { let res = Await this.getdata () console.log(res)} catch (err) {console.log(err)}}Copy the code
Axios principles and source code analysis?
In-depth analysis of Axios source code
www.cnblogs.com/imwtr/p/780…
Juejin. Im/post / 684490… (Vue vs. React)