web123456

Summary of common Vue problems and solutions

Q1:Install timeout

The programs are as follows.

cnpm : Domestic mirror version of npm
/*
cnpm website: /
*/
npm install -g cnpm --registry=https://registry.npm.taobao.org

// Most of cnpm's commands are the same as npm's, such as installing and uninstalling.
The great yarn and npm change source method

// Using the nrm module : /package/nrm
npm config : npm config set registry https://registry.npm.taobao.org
yarn config : yarn config set registry https://registry.npm.taobao.org
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Q2:Install some packages that need to be compiled: no python installed, build failed, etc.

Because some npm packages need to be installed in a compiled environment, mac and linux are fine, most of them are complete window users rely on some libraries of visual studio and python 2+, windows partners are installed: windows-build-tools python

Q3:can't not find 'xxModule' - Some dependency or module cannot be found.

In this case, the general error message can be seen which package throws the message. In general, you can uninstall the 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; as follows

export default {
  name: 'page-router-view',
      data () {
      return {
        tabs: [
          {
            title: 'Financial information',
            url: '/userinfo'
          },
          {
            title: 'Account Information',
            url: '/userinfo/base'
          }
        ]
      }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Why return a data object? The official explanation is as follows: data must be declared as a function that returns an initial data object, since the component may be used to create multiple instances. If data remains a pure object, all instances will share a reference to the same data object! In short, with component reuse, there is no chance of having data pointing to one place at the same time, creating a problem that can affect the whole system...

Q5:I add an event to the native control inside the component, how come it doesn't work!!!!

<!--For example, if a third-party framework is used,Or some encapsulated built-in component; Then you want to bind the event-->
<!--// Error Example 1 - >
<el-input placeholder="Please enter a specific spending amount." @mouseover="test()"></el-input>
<!--// Error Example 2 - >
<router-link :to="" @click="toggleName=''">
  <i :class="['fzicon',]"></i>
  <span>{{item.menuName}}</span>
</router-link>
<!--Neither of the above examples triggers the event!!!-->
<!--trace something to its source,One less modifier.native-->
<router-link :to="" @click.native="toggleName=''">
  <i :class="['fzicon',]"></i>
  <span>{{item.menuName}}</span>
</router-link>
<!--It's in the official documentation.,A bunch of people don't want to see it,,Fuck-->
<!--https://cn.vuejs.org/v2/guide/components.html#Bind native events to components-->
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

Q6:I used axios , why IE browser does not recognize (IE9+)

That's because the whole IE family doesn't support promise, solution.

npm install es6-promise
// Just introduce it at
// ES6 polyfill
require("es6-promise").polyfill();
  • 1
  • 2
  • 3
  • 4

Q7: I used = inside the function, why it throws Cannot set property 'xxx' of undefined.

This is the this trope again... this is bound to the current running context...

Generally you can use axios or other promise , or setInterval which by default points to the outermost global hook.

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

Solution.

Staging: cache this inside function , let that = this;(let is es6, es5 uses var) Arrow functions.
will forcibly associate the current runtime region with the context of this; the

Q8:I see some Vue tutorials have such writing style, what does it mean @,;.

Take these two examples.

@ : event + modifier , which acts as a click but prevents the default behavior.

:: Custom directives + modifiers. Depending on the directive, modifiers are mostly used to add exact extensions to events, such as stopping events from bubbling, blocking default behavior, accessing native controls, incorporating keyboard shortcuts, and so on.

Can I customize modifiers? Yes, you can. You can customize key-value modifier aliases with global objects:

Q9:Why does my introduced small image render out as data:image/png;base64xxxxxxxxxxx

This one iswebpack The corresponding plugin inside the processing, for less than how many K below the image (the prescribed format) directly to base64 format rendering.

Specific configuration in the inside of the rules inside the url-loader, the benefits of doing so: in the network speed is not good before the content loaded and reduce the number of http requests to reduce the burden on the web server.

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

Roughly speaking, a single component rendering DOM area must have a root element, and no sibling elements can appear. The v-if and v-else-if directives can be used to control other elements to achieve a coexistence state.

To put it bluntly, there is a unique parent, the wrapper; for example, a div can have as many siblings or nests inside it as you want, but no siblings can appear in the outermost element!

Q11:How to solve the cross-domain problem!for exampleNo ‘Access-Control-Allow-Origin’ header is present on the requested resource.

It's such a cliché that I won't go into detail... in general terms.

1: CORS, front and back end to correspond to the configuration, IE10+.
2: nginx reverse proxy, once and for all <-- online environment can use this

offline development mode, such as you use vue-cli, inside the webpack has introduced a proxyTable such a thing, you can also do interface reverse proxy.

// In the config directory, the

proxyTable: {
  "/bp-api": {
    target: "",
    changeOrigin: true,
    // pathRewrite: {
    //   "^/bp-api": "/"
    // }
  }
}


// target : is the actual path to the api's proxy.
// changeOrigin: is the source of the change, must be...
// pathRewrite : it's path redirection, you'll know it!
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

Of course, there are still strong jsonp method! But there are more limitations, more suitable for some special information access!

Q12:The values of the array I need to traverse have been updated, and the values have been assigned, but why the view is not updated!

That's because there are limitations, and the official docs make it very clear that only some modified methods provide the same posture as the native one (yet can trigger view updates).

Generally our more common (besides the magic alteration method) means is to use:this.$set(obj,item,value);

Q13:Why can't I inherit or override the styles between my components!

In single-component development mode, please make sure that css modularization is enabled! That is, scoped (configured in vue-cli, just add this attribute to automatically enable it).

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

Why can't it be inherited or overridden, when every class or id or even tag automatically adds hash after the css! For example:

// Write it like this
.trangle{}
// Compiled, with hash.
.trangle[data-v-1ec35ffc]{}
  • 1
  • 2
  • 3
  • 4

These are configured inside the css-loader!!!!

Q14:After the route mode is changed to history, except for the first time to start the home page, there is no error, refresh the access route are reported as error!

The main page of the query must be configured for the corresponding server... which can also be thought of as a guide to the main routing entry.

Official documents are also available, why there are always people do not like to read the documents, always like to do hand party.

Q15:I want to block the page, or do something before the page comes in, is it possible?

Yes, various router hooks are possible!!!! Of course, memorizing the position of the scroll can also be done, for details, look through the documentation on the official website.

Q16:TypeError: xxx is not a function

This kind of question is clearly a writing problem...can you use your brain!!!!

Q17:Uncaught ReferenceError: xxx is not define

The variable corresponding to data in the instance is not declared, and you get this error when you import the module, so the export is definitely not written properly.

Q18:Error in render function:”Type Error: Cannot read property ‘xxx’ of undefined”

This kind of problem is mostly due to the initialization of the wrong posture; such as the introduction of echart these ... carefully to understand the life cycle, and then the specific initialization.

vue components sometimes do (nested components or props passing initialization)... also basically this problem

Q19:Unexpected token: operator xxxxx

Big brother, this seems to be a syntax error ah, basically is a symbolic problem, the general error report will give which line or which component.

Q20:Npm run build can not be directly accessed after the

Hey man! You should at least have a local server to access it!!!!

Q21:After CSSbackground introduces image packing, the access path is wrong.

Because the packaged image is in the root directory, you use the relative path will be reported error ah...

You can magically change static in the webpack config file to . /static... but it's not recommended. If you drop the image or whatever into the assets directory, and then relative path it, the package will work fine.

Q22:When installing a module, the command window outputs unsupported platform xxx.

Generally two cases, node version incompatibility, system incompatibility.

Solution: Either do not install or fulfill the installation requirements.

Q23:Unexpected tab charatersuch

Usually you use scaffolding initialization with eslint on; either follow the rules, or change the rules; or just turn off the eslint detection inside webpack.

Q24:Failed to mount component: template or render function not defined

Component mounting fails with only a few problems

The component is not properly introduced; the
The mount points are in the wrong order; do it yourself!

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

The component has not been introduced or used correctly.

Import the corresponding components
Declare within components
Declaring tags in the dom area

Q26:axios's post request is not accepted by the backend!

axios default is json format submission, confirm whether the background to do the corresponding support; if you can only accept the traditional form serialization, you need to write their own escape method ... Of course, there is a more economical solution, install a small module qs.

npm install qs -S
// And then just turn it in the right place... Single request works, interceptor works... I wrote it in an interceptor.
// Check out my axios wrapping article for more details.
Serialization of //POST pass parameters (add request interceptor)
Axios.interceptors.request.use(
  config => {
    // Do something before sending the request
    if (
      config.method === "post"
    ) {
      // Serialization
      config.data = qs.stringify(config.data); // ***** escaped here
    }

    // If you have an authentication token, put a token in the header.
    if (localStorage.token) {
      config.headers.Authorization = localStorage.token;
    }
    return config;
  },
  error => {
    Message({
      // Hungry for a message popup component, similar toast.
      showClose: true,
      message: error,
      type: ""
    });
    return Promise.reject(error.data.error.message);
  }
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

Q27:Invalid prop: type check failed for prop “xxx”. Expected Boolean, got String.

The problem is usually that the props type within the component has already been set to accept the range type, and the value you pass is not the type it needs, write the code more rigorously OK?

Q28:Can filters be used for DOM region binding commands?

// No, look at the following example of an error.
<li v-for="(item,index) in range | sortByDesc | spliceText">{{item}}</li>
// The `vue2+` directive can only be used with the term mustache`{{}}` , the correct position is as follows.
<span>{{ message | capitalize }}</span>
  • 1
  • 2
  • 3
  • 4

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

ES6+ (ES2015) the foundation of the go over again ... above in turn: array deconstruction, object deconstruction, object style function, object deconstruction assignment pass.

Q30:My Vue website why UC access is blank or the flex layout is messed up!!!!

Come on, come on, the corner to go up ... UC called the mobile world of IE this title is not for nothing. flexbox layout is messed up, usually you do not write the compatibility program ... is with a variety of prefixes, composite attribute splitting.

UC access to the blank, there is a situation will definitely cause, that is, ES6 code degradation is not thorough enough. Other cases may be routing configuration problems (to rule out), now the development are recommended to introduce on-demand, rely on babel-preset-env to control, in order to achieve packaging volume reduction.

But the consequence of this, some kernels are older... hehehe... bye bye. So it's better to make your code fully ES5!!!! Remember that some features can't be used without a corresponding polyfill, such as ES6's proxy.

Q31:this. s e t ∣ t h i s . set | this. setthis.xxx What does the $ mean? Is it jQuery, does it conflict?

I'll tell you more.

Vue's respond in singing j Q u e r y (math.) and jQuery's cap (a poem)jQuery(used form a nominal expression)It doesn't have anything to do with it, it has nothing to do with it.JavaScriptSame as java.
Vue's be classifier for sealed letters or sealed thin packages install (of eyes) bright one some v u e (used at the end of a declarative sentence for emphasis) inner build letter number (math.) Number so after that lead classifier for dramas, plays or operas in order to is to encapsulate some of vue's built-in functions, and then export them to the beclassifier for sealed letters or sealed thin packagescostume (of an actor in a play)(modal particle intensifying preceding clause)"one" radical in Chinese characters (Kangxi radical 1)measure word indicating a small amount or small number (greater than 1)vue(used form a nominal expression)interiorset upenvelopecriticize (i.e. enumerate shortcomings),like thisempressleadgo outin order tobeginning... this is clearly not the preserve of jQuery; the
jQuery's $ is a selector!!!! Getting the DOM region...the two have completely different roles!

Q32:Error in event handler for “click”:”xxx”

Most of the time, this is a problem with the code you're writing. Your event is triggered, but the component lacks a corresponding implementation or variable, so it throws an event error.

Solution: Look at the error report slowly troubleshooting

Q33: What kinds of newsletters are available for components!

Basically, these are the most commonly used ones.

Father to son: props
Son to Father: emit
Brothers in arms:event bus: is to find an intermediate component to act as apass on informationintermediary
vuex: Information Tree

Q34:Why the user information of vuex should be stored again in the browser(sessionStorage or localStorage)?

Because the vuex store can't do anything about refreshing, it's stored in the browser's cache, and if the user refreshes it, the value is retrieved again.

Q35:"Do you have Vue + Vue Router + Vuex" or any "express + vue + mongodb" project to learn?

Github is full of them, so whoever is asking these questions, use your head!

Q36:Online if nginx, how to deploy? and reverse proxy these!

1. Put the service port of the node side into the server's port 80 to do the reverse proxy, here we use port 3000 for demonstration.

# Define a website variable first to facilitate the management of future port changes that will not affect the subsequent80Other operations of the port
upstream website{
  server 127.0.0.1:3000;
}
 
server {
  listen 80;
#Occupier logic... ...
####
  location / {
        proxy_pass    http://website;
        proxy_redirect default ;
  }
####  
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Q37: "I know Vue, do I need to learn jQuery or native JS?"

jQuery there are many companies in use, the source code can learn a lot of places; native js is fundamental, regardless of which front-end framework, and ultimately are js implementation; only a solid foundation, in order to learn the deeper ...

Frameworks are just a way to speed up development and improve efficiency, but they're not what you need to stay in the business for the long haul; they're not what you need to stay in the business for the long haul.

Front-enders need not only breadth, but also depth...so that they can go further...

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

I don't even need to tell you how to scaffold with webpack yourself; the webpack configuration inside Vue-cli: config/

dev: {
    env: require("./"),
    port: 8080, // Here, if the port is already occupied by another program on the system. Change me, change me !!!!!!
    autoOpenBrowser: true,
    assetsSubDirectory: "static",
    assetsPublicPath: "/",
    proxyTable: {
      "/bp-api": {
        target: "",
        changeOrigin: true,
        // pathRewrite: {
        //   "^/bp-api": "/"
        // }
    }
},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Q39:When to use v-if,what to use v-show!

Let's start with the core differences between the two ;)

v-if : DOM area is not generated, not inserted into the document ... and so on when the conditions are established before dynamically inserted into the page! Some need to traverse the array object or value, it is best to use this product control, until the value to handle traversal, otherwise some operations too fast will report an error, such as data has not been requested to!
v-show: DOM area in the component rendering time at the same time rendered, just simply with css to hide, for the drop-down menu, collapsing the menu of these data basically not much change. Use this is the most appropriate ... and can improve the user experience , because it does not lead to page redrawing , DOM operation will be!

In short: use v-show if the DOM structure doesn't change much, use v-if if the data needs to change a lot or the layout needs to change.

Q40:What is it,html5 tag?

You guessed it... html5 does have such a tag, but Vue's template is a bit different, not to be parsed by the browser.

You can be understood as a temporary label, used to facilitate you to write loops, judgment ...

Because ultimately the template doesn't parse into the browser page, it just acts as a wrapper around the Vue parsing process! What we end up seeing is the combined DOM structure processed internally!

Q41:the “scope” attribute for scoped slots …. replaced by “slot-scope” since 2.5

This problem only occurs in old projects when upgrading to vue2.5+, the hint is that scope should now be replaced by slot-scope, but scope can be used for now, and will be removed later.

Q42:Uncaught ReferenceError : Vue is not defined!

Exclude in order.

Is Vue being introduced correctly!
Is Vue Instantiated Correctly!
Vue with the right posture (for example, you directly a Vue variable!!!! which happens to be undefined, so let's analyze the problem).

Q43:ERROR in static/js/ from UglifyJs

I know one of the scenarios where this is reported is when you introduce js, directly into the compressed version of js(); and then webpack has UglifyJs enabled, the duel compression is mostly reported as an error!!!!

Solution: Introduce Standard Uncompressed JS

Q44: Can props pass values without using :(v-bind)!

Yes, you can, but the default type will be parsed as a string! If you want to pass another type, you should bind it.

Q45:Uncaught TypeError : Cannot set property xxx which has only a getter

The problem is that the property you want to manipulate only allows getters, not setters.

The solution? If you use someone else's stuff, you have to follow someone else's routine, or you'll have to do it yourself!

Q46:What the hell is the @ in import xxx from '@/components/layout/xxx' inside the single component!

This is webpack knowledge, see also say it ... webpack can be configured alias (that is, path aliases), played linux or mac know.

As above, for those of you who know how to build your own scaffolding, I don't need to tell you... Take a look inside the vue-cli.

Filename: build ->

resolve: {
    extensions: [".js", ".vue", ".json"], // The range of extensions that can be ignored when importing.
    alias: {
      vue$: "vue/dist/",  
      "@": resolve("src"),  // This is where the aliases come in, e.g. @ means start at /src!!!!
      "~": resolve("src/components")
    }
},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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

All three are preprocessors; the

scss appeared the longest, can do more functionality, but if it is ordinary nested writing, inheritance, mixin ah, these three are similar ... ... will be one of the other two of the rough use of the basic will also be, but some differences in the way of writing.

scss: is written like
css rely on sass : it's actually scss, just written differently... rely on indentation!
less : basically on par with css
stylus: the same, by indentation...like pug(Jade)

Differences in the environment of use.

scss can be compiled with ruby or node-sass.
less can be parsed with or the corresponding loader
Stylus can only be parsed with the help of a loader, which is based on node's

There is also a rising star, the main decoupled, plug-in!!!! That is PostCSS, this is the post-processor! Interested in their own to understand, the above write can be realized with the help of plug-ins!

Q48:Failed to compile with x errors : This dependency was not found !

Compile error, dependency not found! The solution is as follows.

Know the missing module, directly loaded, if you have installed a large module (such as axios) inside the sub-module (dependencies) out of the problem, uninstall and reinstall the entire large module. Because you fill in the whole not necessarily useful!

Q49:SyntaxError: Unexpected identifier;

If there is a syntax error, look at the error message to find the corresponding page to troubleshoot!

Q50: Why does my npm oryarn Installation of dependencies generates lock files, what's the point!

The lock file serves to standardize version numbers, which is useful for teamwork.

If it's not locked, it's not locked according topackage.json inside ^,~ these .

The version number may not be the same for different people, at different times.

Some packages even have some breaking changes, which makes development very difficult!

Q51: Can components be cached?

Yes, keep-alive.

But there is code...occupy memory will be more...so brainless cache all the components!!!!! Not to mention the performance... switch a few times, some hardware can't hold it, and the browser just crashes or gets stuck...

So keep-alive general cache are some list pages, will not have too many operations, more just a result set of replacement ... to the route of the component meta to add a flag bit, combined with the v-if can be added to the cache on demand!

Q52: Difference between dependencies and devDependencies inside!

In fact, if it is not strict, there is no particular difference; if it is strict, it follows the official understanding.

dependencies: core code modules that can be accessed online or by the business, e.g. vue, vue-router.

devDependencies: development modules that you depend on when you're in development mode, perhaps just for parsing code, escaping code, but not generating additional code for production, such as babel-core. How do you install packages under these dependencies?

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

// Can also be written in the easy way (i:install, -S:save, -D:save-dev)

npm i -S xxxx // npm install --save xxxx
npm i -D xxxx // npm install --save-dev xxxx
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Q53: Error installing chromedriver!!!! The posture is right ah npm i -D chromedriver

Well, the great GFW... Solution: Specify a domestic source and install it!

npm install --save-dev chromedriver --chromedriver_cdnurl=http://cdn.npm.taobao.org/dist/chromedriver
  • 1

Q54:Vue ,reactWhich is the best , Angular study? Which one is better for jobs!

Vue belongs to the progressive development, traditional development transition MVVM mode partners, Vue is better to get started, the learning cost is relatively low.

If you have a good foundation and a spirit of compromise, you can choose NG5 or react 16.

NG5 need to learn typescript and rxjs, but also use more new things, such as decorators, back-end injection concepts. ng has its own set of MVVM process.

Vue and React core is just view, you can match your favorite

React's writing method is biased towards functional writing method, and jsx, official own flow, of course, can also be used with ts, I have not been much contact ... so there is a certain learning cost.

As for which one is better to find a job!!!! I'll tell you what...if you only know one framework, you're not a qualified front-end; and if you don't know one framework, you're not a qualified front-end; you're not a qualified front-end.

They want hands-on, problem-solving skills!!!! Skill and treatment are directly proportional!!!

Face and background, education, eloquence can be a plus...but you have to have these qualifications on the basis of which you can consider these!!!!!

Q55:I have a complex component need to have the ability to add and edit at the same time, but the field to maintain the invariance of how to solve the problem

What do you mean by field invariance? It means that, for example, adding and editing share a single piece of data at the same time.

There is one where the routing changes, the component renders the same (without causing re-rendering and destruction of the component!) , but the functionality is different (added and compiled)...

For example, if we cut from edit to add, the data must be blank and unassigned, waiting for us to assign a value.

There's one thing that fits the bill, and that's immutable-js.

This thing simulates the uniqueness of data! Or call it invariance!

Q56: "The first screen loads slower!!!! How to break it! Packaged file file is rather large"

Troubleshoot and confirm in turn.

Reduce the use of third-party libraries , such as jquey these can not be , very little operation dom, and native basic to meet the development.

If you introduce Moment, webpack excludes internationalized language packages.

webpack routinely compresses js, css, and can introduce dlls if you're willing to compromise.

Routing components are lazy loaded.

Add routing transitions and loading waiting effects, although it can not solve the fundamental, but at least let people wait a little more comfortable is not it!!!!

Overall, it's usually not too big after packing.

But what if you want it to be faster? Then you have to use server-side rendering (SSR), which prevents the browser from parsing templates and commands.

Returns an html directly ... and still seo...

Q57: Vue SPA can't be optimized (SEO)! Is there a solution?

can, SSR (server-side rendering can meet your needs), because the request back is a processed html, now vue server-side development framework has such a more popular, as follows.

Q58:Vue can write hybird App one (unambiguous spoken form when spelling out numbers, esp. on telephone or in military)!

Sure, in both directions.

codorva + nativescript
Weex

Q59: Can Vue write desktop?

Sure, there's electron and node-webkit(nw); I only know electron.

electron
electron-vue: Vue-cli scaffolding template for electron

Q60:Vue development, the project still need jQuery?

Scenarios to explore.

If it's an old project and you're just introducing Vue to simplify development, you can still use it...
Reorganize the project? Or start a new project, there is really no need. Development thinking is different, many of the previous DOM operations can now be basically data-driven to achieve, and a small number of compelling DOM operations can be dealt with natively ... ... and can be a small package size, speed and fast, why not!

Retrieved from: Front End Learning Stack
Recorded Learning