Summary of 60 Vue common problems and solutions

Q1: Install timeout (install timeout)

The plans are as follows:

cnpm : 国内对npm的镜像版本
/*
cnpm website: https://npm.taobao.org/
*/
npm install -g cnpm --registry=https://registry.npm.taobao.org

// cnpm 的大多命令跟 npm 的是一致的,比如安装,卸载这些
yarn 和 npm 改源大法

//使用 nrm 模块 : 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.

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, both mac and linux are fine. Most of them are complete. Windows 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 threw 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 the vue instance, the data of a single component must return an object; as follows


export default {
    
    
  name: 'page-router-view',
      data () {
    
    
      return {
    
    
        tabs: [
          {
    
    
            title: '财务信息',
            url: '/userinfo'
          },
          {
    
    
            title: '帐号信息',
            url: '/userinfo/base'
          }
        ]
      }
    }
}

Why return a data object? The official explanation is as follows: data must be declared as a function that returns an initial data object, because the component may be used to create multiple instances. If data were still a pure object, all instances would share a reference to the same data object! In short, when components are reused, data will not be pointed to the same place at the same time, causing broken problems that affect the whole body...

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

<!--比如用了第三方框架,或者一些封装的内置组件; 然后想绑定事件-->
<!--// 错误例子1-->
<el-input placeholder="请输入特定消费金额 " @mouseover="test()"></el-input>
<!--// 错误例子2-->
<router-link :to="item.menuUrl" @click="toggleName=''">
  <i :class="['fzicon',item.menuIcon]"></i>
  <span>{
    
    {
    
    item.menuName}}</span>
</router-link>
<!--上面的两个例子都没法触发事件!!!-->
<!--究其原因,少了一个修饰符 .native-->
<router-link :to="item.menuUrl" @click.native="toggleName=''">
  <i :class="['fzicon',item.menuIcon]"></i>
  <span>{
    
    {
    
    item.menuName}}</span>
</router-link>
<!--明明官方文档有的,一堆人不愿意去看,,Fuck-->
<!--https://cn.vuejs.org/v2/guide/components.html#给组件绑定原生事件-->

Q6: I use axios, why doesn’t IE browser recognize it (IE9+)

那是因为 IE 整个家族都不支持 promise, 解决方案:
npm install es6-promise
// 在 main.js 引入即可
// ES6的polyfill
require("es6-promise").polyfill();

Q7: I used this.xxx= in the function, why is Cannot set property 'xxx' of undefined thrown?

This is this's routine again...this is bound to the current running context...

Generally, you are in axios or other promises, or setInterval, which by default point to the outermost global hook.

To put it simply: "The outermost context is window, and inside vue is Vue object instead of instance!";

solution:

Temporary storage method: cache this first in the function, let that = this; (let is es6, es5 uses var)
Arrow function: will forcibly associate the context with the current running area as this;

Q8: I saw some Vue tutorials with these writing methods, what do they mean @click.prevent,v-demo.ab;

Let’s take these two examples.

@click.prevent: event + modifier, the function is to click but prevent the default behavior.

v-demo.ab: Custom instructions + modifiers. It depends on what instructions you have. Most of the functions of modifiers are to add some specific extended functions to events, such as preventing event bubbling, preventing default behaviors, and 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 the small picture I imported rendered as data:image/png;base64xxxxxxxx?

This is handled by the corresponding plug-in in webpack. Images (specified format) smaller than a certain number of K are directly converted to base64 format for rendering;

The specific configuration is the url-loader in the rules in webpack.base.conf.js. The advantage of doing this is to load the content before the content and reduce the number of http requests to reduce the load on the website server when the network speed is not good.

Q10:Component template shold contain exactly one root element.If you are useing v-if on multiple elements , xxxxx

Generally speaking, the single-component rendering DOM area must have a root element, and no sibling elements can appear. You can use the v-if and v-else-if instructions to control other elements to coexist.

To put it bluntly, there is a unique parent class, the wrapper; for example, a div (parent containing block) can have as many sibling or nested elements inside it, but the outermost element cannot have sibling elements!

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, the front and back ends must be configured accordingly, IE10+
2: nginx reverse proxy, once and for all <-- online environment can use this

In offline development mode, for example, if you use vue-cli, webpack has introduced something like proxyTable, which can also be used as an interface reverse proxy.


// 在 config 目录下的index.js
proxyTable: {
    
    
  "/bp-api": {
    
    
    target: "http://new.d.st.cn",
    changeOrigin: true,
    // pathRewrite: {
    
    
    //   "^/bp-api": "/"
    // }
  }
}

// target : 就是 api 的代理的实际路径
// changeOrigin: 就是是变源,必须是...
// pathRewrite : 就是路径重定向,一看就知道

Of course, there is still the JSONP method that is still strong! However, it has many limitations and is more suitable for some special information acquisition!

Q12: The array value I need to traverse has been updated and the value has been assigned. Why is the view not updated?

That's because there are limitations, and the official documentation also makes it very clear that only some modified methods provide the same usage posture as the original (but can trigger view updates);

Generally, the most commonly used method (except for the magic modification 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 (it is configured in vue-cli, and it will be automatically enabled as long as this attribute is added).

<style lang="scss" scoped></style>

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:

// 写的时候是这个
.trangle{
    
    }
// 编译过后,加上了 hash
.trangle[data-v-1ec35ffc]{
    
    }

These are configured in css-loader!!!

Q14: After the routing mode is changed to history, except for the first start-up homepage, no error is reported, and when refreshing the access route, an error is reported!

The main page for query must be configured for the corresponding server...it can also be considered as the guide for the main routing entrance.

There are also official documents, but there are always some people who don't like to read documents and always like to be a party to do it.

Q15: I want to intercept the page or do something before the page comes in. Is that okay?

Yes, hooks for various routers!! Of course, it is also possible to memorize the scrolling position, check the documentation on the official website for details.

Q16:TypeError: xxx is not a function

This kind of problem 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 import the module and report this error, it must be that 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 sometimes do this (nested components or props transfer initialization)... This is also the basic problem

Q19:Unexpected token: operator xxxxx

Boss, this is a grammatical error at first glance. It is basically a symbol problem. Generally, the error report will give which line or component.

Q20: npm run build cannot be accessed directly after

Boss! You have to at least set up a local server to access it, right?

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 magically 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 the module, the command window outputs unsupported platform xxx

Generally, there are 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 these

Generally, 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

Component mounting failed, there are only a few problems

Components are not introduced correctly;
mount points are in the wrong order; troubleshoot by yourself

Q25:Unknown custom element: - did you register the component correctly?

The component is not introduced correctly or used correctly, please confirm in order.

Import the corresponding component
and declare it in components.
Declare the label in the dom area.

Q26: Axios’ post request cannot be accepted by the background!

Axios submits in json format by default. Please confirm whether the background has corresponding support; if it can only accept traditional form serialization, you need to write an escape method yourself... Of course, there is a more trouble-free solution, install a small module qs .

npm install qs -S
// 然后在对应的地方转就行了..单一请求也行,拦截器也行...我是写在拦截器的.
// 具体可以看看我 axios 封装那篇文章
//POST传参序列化(添加请求拦截器)
Axios.interceptors.request.use(
  config => {
    
    
    // 在发送请求之前做某件事
    if (
      config.method === "post"
    ) {
    
    
      // 序列化
      config.data = qs.stringify(config.data); // ***** 这里转义
    }

    // 若是有做鉴权token , 就给头部带上token
    if (localStorage.token) {
    
    
      config.headers.Authorization = localStorage.token;
    }
    return config;
  },
  error => {
    
    
    Message({
    
    
      //  饿了么的消息弹窗组件,类似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 usually that the props type in the component has set the accepted range type, but the value you pass is not the type it requires. Is it okay to be more rigorous in writing code?

Q28: Can filters be used in DOM areas combined with instructions?

// 不行,看下面的错误例子
<li v-for="(item,index) in range | sortByDesc | spliceText">{
    
    {
    
    item}}</li>
// `vue2+`的指令只能用语 mustache`{
    
    {}}` , 正确姿势如下:
<span>{
    
    {
    
     message | capitalize }}</span>

Q29: […Array],…mapState,[SOME_MUTATION] (state) {}, increment ({ commit }) {} What the hell is this way of writing!

I have gone through the basics of ES6+ (ES2015)...the above are in order: array destructuring, object destructuring, object style functions, object destructuring and assignment passing.

Q30: Why is the UC access to my Vue website blank or the flex layout is messed up!!

Come, come, come around the corner... UC is known as the IE of the mobile world. This title is not called for nothing. The flexbox layout is messy, usually because you haven't written down the compatibility plan...that is, with various prefixes and composite attribute splitting.

There is one situation that will definitely cause UC access to be blank, that is, the ES6 code downgrade is not thorough enough. Other situations may be routing configuration issues (trouble it yourself). Current development recommends introducing it on demand and relying on babel-preset-env to control it. , in order to reduce the packaging volume.

But the consequence of doing this is that some kernels are older...hehe...bye. So it is best to make the code completely ES5!! Remember that some features cannot be used randomly 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's and jQuery'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”

Most of this problem is caused by the code you wrote. Your event is triggered, but there is no corresponding implementation or variable 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?

Basically the most commonly used ones are these;

Pass from father to son: props
from 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, it is saved 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 searches on Github. People who ask these questions should use their brains!

Q36: If nginx is used online, how to deploy it? And reverse proxy and so on!

1. Put the service port of the node into port 80 of the server and use it as a reverse proxy. Port 3000 is used here for demonstration.

#先定义一个website变量,方便管理以后端口的变更,不会影响到后续的80端口其他的操作
upstream website{
    
    
  server 127.0.0.1:3000;
}
 
server {
    
    
  listen 80;
#业户逻辑... ...
####
  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 is a lot to learn from the source code; native js is the foundation, 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 not the foundation of your long-term foothold in this line;
front-end people not only need width, but also depth... Only in this way can we go further...

Q38: npm run dev reports a port error! Error: listen EADDRINUSE :::8080

I don’t need to tell you if you use webpack to build scaffolding yourself; webpack configuration in Vue-cli: config/index.js

dev: {
    
    
    env: require("./dev.env"),
    port: 8080, //  这里这里,若是这个端口已经给系统的其他程序占用了.改我改我!!!!!!
    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 when to use v-show!

Let’s first talk about the core differences between the two;

v-if: The DOM area is not generated, and no document is inserted...it will be 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 control, and wait until the value is obtained before processing the traversal, otherwise some If the operation is too fast, an error will be reported, for example, the data has not been requested yet!
v-show: The DOM area is rendered at the same time when the component is rendered, but is simply hidden using CSS. For drop-down menus and folding menus, the data basically does not change much. Using this is the most suitable... and it can improve the user experience, because it will not cause the page to be redrawn, DOM operations will!

In short: use v-show if the DOM structure does not change much, use v-if if the data needs to be greatly changed or the layout needs to be changed.

Q40: What is the tag of html5?

You guessed it... 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 label, used to facilitate you to write loops and judge...

Because in the end the template will not be parsed into the browser page, it just acts as a wrapping layer during the Vue parsing process! What we finally see is the internally processed 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 can be used temporarily and will be removed in the future.

Q42:Uncaught ReferenceError : Vue is not defined!

Exclude in turn:

Is Vue introduced correctly?
Is Vue instantiated correctly?
Is the posture used by Vue correct (for example, if you directly use a variable of Vue!!! It happens to be undefined, please analyze the specific problem in detail)

Q43:ERROR in static/js/xxxxxxx.js from UglifyJs

I know that one of the situations where this will happen is that the js you introduced is directly imported into the compressed version of js (xxx.min.js); then UglifyJs (which compresses JS) is enabled in webpack, and double compression is used. Most of them will report an error!!

Solution: Introduce standard unminified 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, not setters;

Solution? If you use other people's things, you must follow other people's routines, otherwise you can only do it yourself!

Q46: What is the @ in the import xxx from '@/components/layout/xxx' in a single component?

This is knowledge about webpack. Let me tell you when you see it... webpack can configure alias (that is, path alias). Anyone who has played with Linux or Mac knows this.

It’s still the same as above, if you can build your own scaffolding, I don’t need to tell you... take a look at vue-cli;

File name: build -> webpack.base.conf.js

resolve: {
    
    
    extensions: [".js", ".vue", ".json"], // 可以导入的时候忽略的拓展名范围
    alias: {
    
    
      vue$: "vue/dist/vue.esm.js",  
      "@": resolve("src"),  // 这里就是别名了,比如@就代表直接从/src 下开始找起!!!
      "~": resolve("src/components")
    }
},

Q47: SCSS (SASS) or less, stylus is better!

All three are preprocessors;
scss has been around for the longest time and can do more functions, but if it is an ordinary nested writing method, inheritance, and mixin, these three are almost the same... the superficial usage of one of the other two is basically the same Yes, but there are some differences in the writing:

scss: It is written like css Aligned with
sass: In fact, it is scss, but it is written differently... relying on indentation less
: basically aligned with css
stylus: the same, relying on indentation...same as pug (Jade)

Differences in usage environment:

scss can be compiled with ruby ​​or node-sass,
less can be parsed with less.js or the corresponding loader,
stylus can only be parsed with the help of loader, and its appearance is based on node.

There is also a rising star that focuses on decoupling and plug-in!!! That is PostCSS, which is a post-processor! If you are interested, you can learn about it by yourself. The above writing methods can all 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:

If you know that the corresponding module is missing, install it directly. If there is a problem with the submodule (dependent package) in a large module you have installed (such as axios), uninstall and reinstall the entire large module. Because your completion may not be useful!

Q49:SyntaxError: Unexpected identifier;

Syntax error, look at 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, follow the ^,~ in package.json.

The version numbers installed by different people at different times may not be 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 is code... It will take up a lot of memory... So I cache all the components without thinking!!! Not to mention the performance is better... After switching a few times, some hardware cannot hold it, and the browser crashes or freezes...

Therefore, keep-alive generally caches some list pages, and there will not be too many operations. More is just the replacement of the result set... Add a flag bit to the routing component meta, and combine it with v-if to add cache on demand. up!

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 are relied upon in development mode may only be used to parse code and escape code, but do not generate additional code to the production environment. For example, how to install babel-core packages to the corresponding dependencies?

npm install --save xxxx // dependencies
npm install --save-dev xxxx // devDependencies

//也能用简易的写法(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

Well, great GFW...Solution: Just specify the domestic source installation


npm install --save-dev chromedriver --chromedriver_cdnurl=http://cdn.npm.taobao.org/di

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 the MVVM model, Vue is easier to get started and the learning cost is relatively low.

If you have a good foundation and a spirit of hard work, you can choose NG5 or react 16;

NG5 requires learning typescript and rxjs, and also uses many 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, you can match it with what you like

The writing method of React tends to be functional writing method, as well as jsx. The official one has flow, which of course can also be used with ts. I have not 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-solving skills!!! Technology and salary are directly proportional!!

Appearance and background, academic qualifications, and eloquence can add points...but you must have a foundation of these conditions before you can consider these!!!

Q55: I have a complex component that needs to have the functions of adding and editing at the same time, but the fields must remain unchanged. How can I break this?

How do you understand that fields remain unchanged? That is to say, adding and editing share a copy of data at the same time;

One is that the routing changes, the component rendering is the same (it does not cause the component to be re-rendered and destroyed!), but the functions are different (new addition and compilation)...

For example, when switching from editing to adding, data must be blank and unassigned, waiting for us to assign a value;

There is something that is particularly suitable at this time, and that is immutable-js;

This thing can simulate the uniqueness of data! Or called immutability!

Q56: "The first screen is loading slowly! Why is it broken? The packaged file is relatively large."

Exclude and confirm in turn:

Reduce the use of third-party libraries, such as jquey, which can be eliminated. DOM operations are rarely used, and the native ones are 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 may not solve the root cause, but at least it will make the wait a little more comfortable, right!!!

Overall, it is generally not too big after packaging;

But if you want to be faster? Then you can only use server-side rendering (SSR), which can avoid the browser parsing templates and instructions;

Directly return an html...it can also be used for SEO...

Q57: Vue SPA cannot be optimized (SEO)! Is there a solution?

Yes, SSR (server-side rendering can meet your needs), because the request comes back as processed HTML. Nowadays, Vue's server-side development framework has such a popular one, as shown below Nuxt.js.

Q58: Can Vue write hybrid App?

Of course you can, both 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, is jQuery still needed in the project?

Discuss by case:

If it’s an old project, it’s simply introducing Vue to simplify development, so you can still use it...
Refactoring the project? Or launching a new project, it’s really unnecessary. The development idea is different. Many operations that used to be operated with DOM can now be basically data-driven, while A small amount of unavoidable DOM operations can be done natively... and it can be packaged in a small size and fast, so why not do it!

This article is reprinted from: JS Daily Question
WeChat public account: JS Daily Question

Guess you like

Origin blog.csdn.net/weixin_45849417/article/details/128984697