Summary of 60 Vue common problems and solutions


Q1: There are several installation timeout
solutions: cnpm: Domestic mirror version of npm
/*
cnpm website: https://npm.taobao.org/
*/
npm install -g cnpm --registry=https:/ /registry.npm.taobao.org
// Most of the commands of cnpm are consistent with npm, such as installation and uninstallation of these
yarn and npm source modification methods
//Use nrm module: www.npmjs.com/package/nrm
npm config: npm config set registry https://registry.npm.taobao.org
yarn config : yarn config set registry https://registry.npm.taobao.org

Q2: Install some packages that need to be compiled: prompts that python is not installed, build fails, etc.
Because some npm package installation requires a compilation environment, mac and linux are fine, most of them are complete. Window users rely on some libraries of visual studio and python 2+ , Windows friends all install: windows-build-tools python 2.x

Q3: can't not find 'xxModule' - Some dependencies or modules cannot be found.
In this case, you can usually see which package is throwing the information in the error message. Generally, you can uninstall this module, install it and reinstall it.

Q4: data functions should return an object.
The problem is that within a Vue instance, the data of a single component must return an object; the following
export default { name: 'page-router-view',data () { return { tabs: [{ title: 'Financial information',url: '/userinfo'},{ title: 'Account information',url: '/userinfo/base'}]} }}?The official explanation is as follows: data must be declared as A function that returns an initial data object, since components may be used to create multiple instances. If data is still a pure object, all instances will share a reference to the same data object! In short, under the reuse of components, it will not cause data to point to one place at the same time, creating a broken problem that affects the whole body...
















Q5: I added an event to the native control in the component, why didn't it take effect!!!

<el-input placeholder="Please enter a specific consumption amount" @mouseover="test()">

<router-link :to=“item.menuUrl” @click=“toggleName=‘’”>

{ {item.menuName}}

<router-link :to=“item.menuUrl” @click.native=“toggleName=‘’”>

{ {item.menuName}}

Q6: I used axios, why IE browser does not recognize (IE9+)
that is because the whole family of IE does not support promise, solution:
npm install es6-promise
// Just import it in main.js
// ES6 polyfill
require ("es6-promise").polyfill();

Q7: I used this.xxx= in the function, why did it throw Cannot set property 'xxx' of undefined;
this is the routine of this again...this is bound to the current running context...
generally you are in axios or other promise , or setInterval are the global hooks that point to the outermost layer by default.
Simply put: "The outermost context is the window, and the Vue object is the Vue object instead of the instance!"; solution:
temporary
storage method: inside the function Cache this first, let that = this; (let is es6, es5 uses var)
Arrow function: will forcibly associate the context where the current running area is this;

Q8: I see that some Vue tutorials have such a way of writing, what does it mean? @click.prevent, v-demo.ab; let’s
take these two examples.
@click.prevent: event + modifier, the function is to click but Also prevents the default behavior.
v-demo.ab: Custom command + modifier. It depends on your specific command. Most of the modifiers are used to add some exact extension functions to the event, such as preventing event bubbling, preventing default behavior, accessing native controls, Incorporate keyboard shortcuts and more.
Can I customize the modifier? It is also possible. Key value modifier aliases can be customized through the global config.keyCodes object:

Q9: Why is my imported small image rendered as data:image/png;base64xxxxxxxx
This is processed by the corresponding plug-in in webpack. For images smaller than K or less (in the specified format), they are directly converted to base64 format for rendering
; Configure the url-loader in the rules in webpack.base.conf.js. The advantage of doing this is: when the network speed is not good, load it before the content and reduce the number of http requests to reduce the burden on the website server.

Q10: Component template should contain exactly one root element. If you are using v-if on multiple elements, xxxxx
generally means that a single component rendering DOM area must have a root element, and no sibling elements can appear. You can use v-if and v-else-if directives to control the state in which other elements achieve co-existence.
Another straightforward explanation is that there is a unique parent class, the wrapper; for example, a div (parent containing block) can have as many siblings or nesting inside, but the outermost element cannot appear at the same level!

Q11: How to solve cross-domain problems! For example, No 'Access-Control-Allow-Origin' header is present on the requested resource.
This kind of problem is a commonplace, so I won't go into details... Let's talk about it in general;
1: CORS, front and rear ends All must be configured accordingly, IE10+
2: nginx reverse proxy, once and for all <-- This
offline development mode can be used in the online environment. For example, if you use vue-cli, the webpack in it has introduced something like proxyTable, which can also be used Make an interface reverse proxy.
// index.js proxyTable in the config directory
: { “/bp-api”: { target: “http://new.d.st.cn”,changeOrigin: true,// pathRewrite: { // “^ /bp-api”: “/”// }}}// target: It is the actual path of the api agent// changeOrigin: It is the change source, it must be...// pathRewrite: It is the path redirection, you can know it at a glanceOf course, there is still a strong jsonp method! However, it has many limitations and is more suitable for some special information acquisition!











Q12: The value of the array I need to traverse has been updated, and the value has been assigned. Why is the view not updated?
That is because of limitations. The official document also makes it very clear that only some modified methods provide the same as the original. Use gestures (but can trigger view updates);
generally, the more common method we use (except the magic change method) is to use: this.$set(obj,item,value);

Q13: Why can’t the styles between my components be inherited or overridden?
In single-component development mode, please confirm whether the css modularization function is turned on! That is, scoped (configured in vue-cli, as long as this attribute is added, it will be automatically enabled ).

Why can't it be inherited or overridden? Because each class or id or even label will automatically add a hash after the css! For example: // When
writing, it is this
.trangle{}
// After compilation, the hash is added
. tangle[data-v-1ec35ffc]{}
These are configured in css-loader!!!

Q14: After the routing mode is changed to history, no error is reported except for the first startup home page, and an error is reported when refreshing the access route! The
main page of the query must be configured for the corresponding server...It can also be considered as the guide of the main route entry.
There are also official documents, because there are always people who don't like to read documents, and always like to be a party.

Q15: I want to intercept the page, or do something before the page comes in, is it okay?
Yes, hooks for various routers!! Of course, memorizing the scroll position can also be done. For details, check the documentation on the official website.

Q16: TypeError: xxx is not a function
is obviously a problem with the writing method... Can you use your brain!!

Q17: Uncaught ReferenceError: xxx is not define
The variable corresponding to the data in the instance is not declared. If you report this error when you import the module, it must be because the export is not written properly.

Q18: Error in render function: "Type Error: Cannot read property 'xxx' of undefined"
Most of these problems are caused by incorrect initialization posture; such as introducing echart... carefully understand the life cycle, and then perform specific initialization;
vue components have Sometimes it happens too (nested components or props transfer initialization)... This is also the basic problem

Q19: Unexpected token: operator xxxxx
Boss, this is a syntax error at first glance. It is basically a symbol problem. Generally, the error report will give which line or component.

Q20: After npm run build, you can’t access it directly,
sir! At least you have to set up a server locally to access it!!

Q21: After CSSbackground introduces image packaging, the access path is wrong.
Because the packaged image is in the root directory, you will definitely get an error if you use a relative path... You
can magic change the static in the webpack configuration file to ./static... but it is not recommended. If you throw the image or something into the assets directory and use a relative path, it will be normal after packaging.

Q22: When installing a module, the command window outputs unsupported platform xxx
. There are generally two situations: the node version is incompatible and the system is incompatible;
solution: either do not install it or meet the installation requirements;

Q23: Unexpected tab charater
usually means that you turn on eslint when initializing with scaffolding; you either follow the rules or change the rules; or you directly turn off the eslint detection in webpack.

Q24: Failed to mount component: template or render function not defined
The component failed to mount. There are only a few problems.
The component was not introduced correctly;
the order of the mount points was wrong; troubleshoot by yourself.

Q25: Unknown custom element: - did you register the component correctly?
The component was not introduced or used correctly. Confirm in order.
Import the corresponding component. Declare it
in components.
Declare the label in the dom area.

Q26: Axios’s post request cannot be accepted by the backend!
Axios submits in json format by default, check whether the backend supports it; if you can only accept traditional form serialization, you need to write an escape method yourself…Of course A more trouble-free solution is to install a small module qs.
npm install qs -S
// and then turn it in the corresponding place... a single request is fine, and an interceptor is also fine... I wrote it in the interceptor. // The specifics
can Take a look at my axios encapsulation article
//POST serialization of parameters (add request interceptor)
Axios.interceptors.request.use(
config => { // do something before sending the requestif (config.method == = "post") { // serializeconfig.data = qs.stringify(config.data); // ***** escape here}






// 若是有做鉴权token , 就给头部带上token
if (localStorage.token) {
  config.headers.Authorization = localStorage.token;
}
return config;

},
error => { Message({ // Ele.me’s message pop-up component, similar to toast showClose: true, message: error, type: “error.data.error.message” }); return Promise.reject(error .data.error.message); } );








Q27: Invalid prop: type check failed for prop “xxx”. Expected Boolean, got String.
This kind of problem is generally that the props type in the component has been set to accept the range type, but the value you pass is not the type it needs , is it okay to be more rigorous when writing code?

Q28: Can filters be used for DOM region combination commands?
// No, see the error examples below

  • { {item}}
  • // The command of `vue2+` can only use mustache`{ {}}`, the correct posture is as follows: { { message | capitalize }}

    Q29: […Array],…mapState,[SOME_MUTATION] (state) {},increment ({ commit }) {} What the hell is this writing method! Go
    through the basics of ES6+ (ES2015)… The above sequence: array deconstruction, Object destructuring, object style functions, object destructuring assignment passing.

    Q30: My Vue website, why is the UC access blank or the flex layout is messed up!!
    Come, come, walk around the corner... UC is known as the IE of the mobile world. This title is not for nothing. The layout of flexbox is messed up. Generally, you didn’t write the compatibility scheme...that is, with various prefixes and compound attribute splitting.
    UC access blank, there is a situation that will definitely cause, that is, the code degradation of ES6 is not thorough enough. Other situations may be routing configuration problems (to be ruled out by yourself), and the current development is recommended to import on demand, relying on babel-preset-env to control , in order to reduce the packaging volume.
    But the consequences of doing so, some kernels are older...hehe...bye. So it is best to write the code completely in ES5!! Remember that some features cannot be used indiscriminately, and there is no corresponding polyfill, such as ES6 proxy

    Q31:this. s e t ∣ t h i s . set | this. se t t hi s . xxx What does this $ mean? Is it from jQuery? Will it conflict?
    Let me explain in detail.
    Vue'sand j Q uery's and jQuery'sIt has nothing to do with jQuery, just like JavaScript and java. Vue encapsulates some
    ofvue's built-in functions, and then exports them, so it encapsulates some of vue's built-in functions, and then exports them asIt encapsulates some built-in functions of vu e .Then the export starts with ... This is obviously not a patent of jQuery;
    jQuery's $ is a selector!! Get the DOM area... The two functions are completely inconsistent!

    Q32: Error in event handler for “click”:”xxx”
    This problem is mostly caused by a problem with the code you wrote. Your event is triggered, but the corresponding implementation or variables are missing inside the component, so an event error is thrown.
    Solution: Watch the error and troubleshoot slowly

    Q33: What are the types of communication between components?
    These are the most commonly used ones;
    father to son: props
    to son to father: emit
    brother communication: event bus: just find an intermediate component to serve as an information transfer intermediary
    vuex: information tree

    Q34: Why does vuex user information need to be stored in the browser (sessionStorage or localStorage)?
    Because the vuex store cannot be refreshed and is stored in the browser's cache. If the user refreshes, the value will be retrieved again;

    Q35: "Is there any project to learn about Vue + Vue Router + Vuex" or "express + vue + mongodb"? There are
    a lot of them on Github. People who ask these questions should use their brains!

    Q36: If nginx is used online, how to deploy it? And reverse proxy!
    1. Put the service port of the node into the 80 port of the server to do the reverse proxy. The 3000 port is used here for demonstration
    #First define a website variable , to facilitate management of future port changes, and will not affect other subsequent operations on port 80
    upstream website{ server 127.0.0.1:3000;}server { listen 80;#Business account logic...




    location / { proxy_pass http://website; proxy_redirect default ; } } Q37: "I know Vue, do I still need to learn jQuery or native JS?" jQuery is still used by many companies, and there are many places to learn from the source code; native js is fundamental , no matter which front-end framework it is, it is ultimately implemented by js; only with a solid foundation can you learn more deeply... The framework only speeds up development and improves efficiency, but it is not the foundation for your long-term foothold in this industry; front-end people not only need width, You also need depth... only then can you go further...







    Q38: npm run dev reports a port error! Error: listen EADDRINUSE :::8080
    If you use webpack to build scaffolding yourself, I don’t need to tell you; webpack configuration in Vue-cli: config/index.js
    dev: { env: require(" ./dev.env”),port: 8080, // Here, if this port is already occupied by other programs in the system, change it!autoOpenBrowser: true,assetsSubDirectory: “static”,assetsPublicPath: “/ ",proxyTable: { "/bp-api": { target: "http://new.d.st.cn",changeOrigin: true,// pathRewrite: { // "^/bp-api": "/ ”// }}},













    Q39: When to use v-if and what to use v-show!
    Let’s talk about the core differences between the two first;
    v-if: The DOM area is not generated, and the document is not inserted...and then dynamically inserted into the page when the conditions are met! For some array objects or values ​​that need to be traversed, it is best to use this product to control, and wait until the value is processed before processing the traverse, otherwise some operations are too fast and an error will be reported, such as the data has not been requested yet! v-show: DOM area is rendered in the
    component At the same time, it is rendered at the same time, but it is simply hidden with css. For the drop-down menu and the folding menu, the data basically does not change much. This is the most suitable... and it can improve the user experience, because it will not cause the page to be redrawn, DOM operation Yes!
    In short: use v-show if the DOM structure does not change much, use v-if if the data needs to be changed a lot or the layout changes

    Q40: What is it? Is it an html5 tag?
    You guessed it right... there is such a tag in html5, but Vue's template is a little different and is not parsed by the browser.
    You can understand it as a temporary tag, used to facilitate you to write loops and judgments...
    Because in the end the template will not be parsed to the browser page, it just acts as a wrapping layer in the Vue parsing process! In the end, what we see is the internal processing The final combined DOM structure!

    Q41: the “scope” attribute for scoped slots …. replaced by “slot-scope” since 2.5.
    This problem only occurs when the old project is upgraded to vue2.5+. The prompt is that scope needs to be replaced by slot-scope now, but scope Available for now, will be removed later

    Q42: Uncaught ReferenceError: Vue is not defined!
    Exclude in turn: Is
    Vue imported correctly!
    Is Vue instantiated correctly!
    Is the posture used by Vue correct (for example, you directly have a Vue variable!!! It just happens to be undefined, and specific problems are analyzed in detail Bar)

    Q43: ERROR in static/js/xxxxxxx.js from UglifyJs
    I know that this situation will be reported in one of the situations, that is, the js you introduced is the compressed version of js (xxx.min.js) directly introduced; then in webpack UglifyJs (compressed JS) is also enabled, most of the double compression will report an error!!
    Solution: Introduce standard uncompressed JS

    Q44: Can props pass values ​​without using: (v-bind)?
    Yes, but the type passed by default will be parsed into a string! If you want to pass other types, the binding is still binding.
    Q45: Uncaught TypeError: Cannot set property xxx which has only a getter.
    The problem is that the property you want to operate only allows getters and does not allow setters;
    the solution? If you use other people's things, you must follow other people's routines, otherwise you can only Make enough food and clothing by yourself!

    Q46: What is the @ in the import xxx from '@/components/layout/xxx' in a single component?
    This is webpack knowledge, tell me when you see it... webpack can configure alias (that is, path alias) , Anyone who has played with linux or mac knows it.
    Still as above, I don’t need to say if you can build your own scaffolding...Look at the inside of vue-cli; file name:
    build -> webpack.base.conf.js
    resolve: { extensions: [“.js”, “.vue”, ".json"], // The range of extensions that can be ignored when importingalias: { vue$: "vue/dist/vue.esm.js","@": resolve("src"), // here is Alias, for example, @ means searching directly from /src!!!"~": resolve("src/components")}},






    Q47: SCSS (SASS) is better than less and stylus!
    All three are preprocessors;
    scss has been around for the longest time and can do more functions, but if it is a common nested writing method, inheritance, and mixin, these three are almost the same ...I can basically use one of the other two in a superficial way, but there are some differences in writing:
    scss: written like css Aligned with
    sass: In fact, it is scss, but written differently... relying on indentation
    less: similar to css Basically close to
    stylus: the same, relying on indentation... same as pug (Jade)
    Differences in use environment:
    scss can use ruby ​​or node-sass to compile
    less can use less.js or the corresponding loader to parse
    stylus can only use loader to parse, it The emergence of is based on node.
    There is also a rising star, which focuses on decoupling and plug-in!!! That is PostCSS, which is a post-processor! Those who are interested can find out by themselves, and the above writing methods can be realized with the help of plug-ins!

    Q48: Failed to compile with x errors: This dependency was not found!
    Compilation error, the corresponding dependency was not found! The solution is as follows:
    know that the corresponding module is missing, install it directly, if it is a large module that you have already installed (such as axios) There is a problem with the submodule (dependent package), uninstall and reinstall the entire large module. Because your completion may not be useful!

    Q49: SyntaxError: Unexpected identifier;
    syntax error, see the error message to find the corresponding page for troubleshooting!

    Q50: Why does my npm or yarn installation dependency generate a lock file? What is its use? The
    function of the lock file is to unify the version number, which is very helpful for team collaboration;
    if there is no lock, according to the ^ in package.json ,~these.
    The version numbers installed by different people at different times are not necessarily consistent;
    some packages even have breaking changes (destructive updates), making it difficult for development to proceed smoothly!

    Q51: Can components be cached?
    Yes, use keep-alive;
    but there are codes...it will take up more memory...so it is brainless to cache all components!!! Not to mention the performance is good...switching several times, some hardware can't hold Live, the browser crashes or freezes directly...
    So keep-alive generally caches some list pages, there will not be too many operations, and more is just the replacement of the result set...Add a flag to the routing component meta, Combined with v-if, you can add caching on demand!

    Q52: The difference between dependencies and devDependencies in package.json!
    In fact, if it is not strict, there is no special difference; if it is strict, follow the official understanding;
    dependencies: store core code modules that can be accessed online or by business, such as vue, vue- router;
    devDependencies: The development modules that depend on in development mode may only be used to parse codes and escape codes, but do not generate additional codes to the production environment, such as babel-core, how to install packages to the corresponding dependencies What?
    npm install --save xxxx // dependencies
    npm install --save-dev xxxx // devDependencies
    // can also use simple writing (i:install,-S:save,-D:save-dev)
    npm i - S xxxx // npm install --save xxxx
    npm i -D xxxx // npm install --save-dev xxxx
    Q53: An error is reported when installing chromedriver!! The posture is correct npm i -D chromedriver
    , great GFW... solution: Just specify the domestic source installation
    npm install --save-dev chromedriver --chromedriver_cdnurl=http://cdn.npm.taobao.org/dist/chromedriver

    Q54: Which one is better to learn, Vue, React, or Angular? Which job is easier to find!
    Vue is a progressive development. For those who transition from traditional development to MVVM model, Vue is easier to get started and the learning cost is relatively low.
    If you have a good foundation and are willing to work hard, you can choose NG5 or react 16;
    NG5 requires learning typescript and rxjs, and also uses more new things, such as decorators and back-end injection concepts. ng has its own set of MVVM processes ;
    The core of Vue and React is just view, which can be matched with your favorite
    React writing style, which prefers functional writing style, and jsx. The official one has flow, which of course can also be paired with ts. I haven’t had much contact with it...so there is a certain learning cost;
    As for which one is easier to find a job!!! Let me tell you... If you only know one framework, it is not a qualified front-end; what
    people want is hands-on ability and solution ability!!! Technology and salary are directly proportional!!
    Appearance and background , academic qualifications and eloquence can be extra points...but you must have these conditions before you can consider them!!!

    Q55: I have a complex component that needs to have the functions of adding and editing at the same time, but how do I break the field if it remains unchanged? How do I understand that the field remains immutable? That is to say,
    adding and editing share a piece of data at the same time;
    one way is The route has changed, the component rendering is the same (it does not cause the component to be re-rendered and destroyed!), but the functions are different (add and compile)... For example, when switching
    from editing to adding, the data must be blank and unassigned, waiting for us to go Assignment;
    something is particularly suitable at this time, and that is immutable-js;
    this thing can simulate the uniqueness of data! Or it is called immutability!

    Q56: "The first screen is slow to load! Why is it broken! The packaged file is relatively large."
    Exclude and confirm in order:
    Reduce the use of third-party libraries, such as jquey, and rarely operate DOM, and the native version is basically sufficient for development.
    If moments are introduced, webpack excludes internationalized language packages.
    Webpack generally compresses js and css. If you are willing to put in the effort, you can also import dlls.
    Routing components use lazy loading.
    Adding routing transition and loading waiting effects, although it can't solve the root cause, but at least it makes people feel comfortable, isn't it!!! Overall, it is generally not
    too big after packaging;
    but if you want to be faster? Then you can only use the service Side-side rendering (SSR) can prevent the browser from parsing templates and instructions; it
    directly returns an HTML...it can also be used for SEO...

    Q57: Vue SPA cannot be optimized (SEO)! Is there a solution
    ? SSR (server-side rendering can meet your needs), because the request comes back as a processed HTML. Now the server-side development framework of vue has Such a popular one is Nuxt.js below.

    Q58: Can Vue write hybrid App?
    Of course, two directions.
    codorva + nativescript
    Weex

    Q59: Can Vue be written on the desktop?
    Of course, there are electron and node-webkit (nw); I only know about electron;
    electron
    electron-vue: Vue-cli scaffolding template for electron

    Q60: For Vue development, do you still need jQuery in the project?
    Discussion according to the situation:
    If it is an old project, just simply introduce Vue to simplify development, you can still use it...
    Refactor the project? Or start a new project, it is really unnecessary. The development idea is different , many DOM operations that used to be used in the past can basically be realized by data-driven, and a small amount of unavoidable DOM operations can be done natively... and can be packaged in a small size and fast, so why not do it!

Guess you like

Origin blog.csdn.net/longxiaobao123/article/details/132778060