Summary of ultra-comprehensive use of vue. js and summary of vue. js

Source: Internet
Author: User

Summary of ultra-comprehensive use of vue. js and summary of vue. js

I. Vue. js Components

Use vue. js build Components

Vue.component('componentName',{ /*component*/ });

Note that the component must be registered before use, that is:

Vue.component('mine',{  template:'#mineTpl',  props:['name','title','city','content'] }); var v=new Vue({ el:'#vueInstance', data:{  name:'zhang',  title:'this is title',  city:'Beijing',  content:'these are some desc about Blog' }});

If an error is reported in turn, it indicates that the component is used first, but the component is not registered.

After webpack reports an error, Usewebpack --display-error-detailsTroubleshooting is possible.

Ii. Command keep-alive

When reading the demo, you can see that it is written in vue-router.keep-alive,keep-aliveMeaning:

If you keep the switched component in the memory, you can retain it or avoid re-rendering. You can addkeep-aliveCommand

<component :is='curremtView' keep-alive></component>

3. How to Make css only play a role in the current component

Each vue component can define its own css and js. If you want the css written in the component to only work for the current component, you only need to write scoped in the style, that is:

<style scoped></style>

Iv. Insert images cyclically in vuejs

When writing a loop, write the following code:

<div class="bio-slide" v-for="item in items">  </div>

A warning is displayed on the console.
[Vue Warn]: src="{{item.image}}": interpolation in "src" attribute will cause a 404 request. Use v-bind:src instead.This indicates that interpolation in the "src" attribute will result in 404 requests. Usev-bind:src.

So replace it with the following:

<div class="bio-slide" v-for="item in items">  </div>

It is important to note that v-bind cannot be used for writing {} again. According to the official statement:

<a v-bind:href="url" rel="external nofollow" ></a>

Here, href is a parameter, which tells the v-bind command to bind the href feature of the element to the value of the expression url. You may have noticed that feature interpolation can be used.href="{{url}}" rel="external nofollow" Get the same result: That's right, and in fact, the internal feature interpolation will be converted into v-bind binding.

5. Bind value to a dynamic attribute of the Vue instance

For the single-choice button, check box and select box options, the value bound to the v-model is usually a static string (for the selected box, it is a logical value ):

<! -- 'Toggle 'is true or false --> <input type = "checkbox" v-model = "toggle">

However, if you want to bind a value to a dynamic attribute of the vue instance, you can use v-bind, and the value of this attribute can be a string. For example, bind the Checkbox value to a dynamic attribute of the vue instance:

<input  type="checkbox" v-model="toggle" v-bind:true-value="a" v-bind:false-value="b"><p>{{toggle}}</p>

After binding, it does not mean that you can switch from true to false to a and B after clicking. Because dynamic a and B are defined here, it cannot be displayed directly.

// Vm. toggle === vm. a // vm. toggle === vm. B when not selected

Therefore, define a and B in data, that is:

new Vue({ el:'...', data:{ a:'a', b:'b'  }});

Vi. Fragment instance

In the following situations, the instance is converted into a fragmented instance:

  1. The template contains multiple top-level elements.
  2. The template only contains plain text.
  3. The template contains only other components (other components may be a fragment instance ).
  4. The template contains only one element instruction, such<partial>Or vue-router's<router-view>.
  5. The template root node has a process control command, as shown in figurev-ifOrv-for.

In these cases, the instance has an unknown number of top-level elements, which treat its DOM content as fragments. The fragment instance still correctly renders the content. However, it does not have a root node. Its $ el points to an anchor node, that is, an empty text node (in development mode, it is a comment node ).

But more importantly, the non-Flow Control commands on component elements, non-prop features and transitions will be ignored because there is no root element for binding:

<! -- No, because there is no root element --> <example v-show = "OK" transition = "fade"> </example> <! -- Props can --> <example: prop = "someData"> </example> <! -- Process control is acceptable, but there cannot be a transition --> <example v-if = "OK"> </example>

Fragment instances are also useful, but normally a component has a better root node, which ensures correct conversion of commands and features on component elements, and slightly better performance.

VII. Route nesting

Nested routing will render other components to this component, instead of redirecting the entire page to the router-view itself, rendering the component to this position, the page will be rendered to the root component and written at the beginning of Route Configuration:

var App = Vue.extend({ root });router.start(App,'#app');

First, register the root component to render the pages configured in the route, and then mount the root component to the elements matching the # app.

8. Multiple methods for displaying different texts based on different conditions

v-if,v-elseYou can select conditions. However, if you select multiple consecutive conditions, you need to use computed. For example, the 'empty' string is displayed when nothing is written in the input box. Otherwise, the content in the input box is displayed. The Code is as follows:

<div id="test"> <input type="text" v-model="inputValue"> 

IX. Vuejs change detection problems

1. detection array

Due to javascript restrictions, vuejs cannot detect the following array changes:

Directly set the index element, as shown in figurevm.item[0]={};

Modify the data length, as shown in figurevm.item.length.

To Solve Problem 1, Vuejs expands the Observation Array and adds$set()Method:

// Same as 'example1. items [0] =... ', but can trigger view update example1.items. $ set (0, {childMsg:' Changed! '})

Question 2: replace items with an empty array.

Besides$set() , Vuejs also added the Observation Array$remove()Method, used to find and delete elements from the target array, called internallysplice().

Therefore, you do not need:

var index = this.items.indexOf(item)if (index !== -1) { this.items.splice(index, 1)}

Only:

this.items.$remove(item);

2. Check objects

As shown by ES5, Vuejs cannot detect the addition or deletion of object attributes. Because Vuejs converts attributesgetter/setterTherefore, attributes must be in the data object so that Vuejs can convert them to respond. For example:

Var data = {a: 1} var vm = new Vue ({data: data}) // 'vm. a' and 'data. a' now the response vm. B = 2 // 'vm. B 'is not the response data. B = 2 // 'data. B 'not responding

However, there is a way to add attributes after the instance is created and make it responsive. For Vue instances, you can use$set(key,value)Instance method:

Vm. $ set ('B', 2) // 'vm. B 'and 'data. B' are responding now

For common data objects, you can use the global method.Vue.set(object, key, value):

Vue. set (data, 'C', 3) // 'vm. c' and 'data. c' are responding now

Sometimes you want to add some attributes to an existing object, suchObject.assign() Or _.extend() Add attributes. However, new attributes added to an object do not trigger updates. In this case, you can create a new object, including the attributes and new attributes of the original object:

// Do not use 'object. assign (this. someObject, {a: 1, B: 2}) 'This. someObject = Object. assign ({}, this. someObject, {a: 1, B: 2 })

10. vuejs page flashes {message }}

The vuejs command contains v-cloak, which is kept on the element until the end of the associated instance compilation. And CSS rules such[v-cloak]{display:none}When used together, this command can hide uncompiled Mustache labels until the instance is ready.

The usage is as follows:

[v-cloak]{ display:none;}<div v-cloak>{{message}}</div>

In this way, <div> is not displayed until the compilation ends.

11. Use of v-model in a v-for Loop

Sometimes it is necessary to generate input cyclically, bind it with v-model, and operate it with vuejs. At this time, we can write an array in v-model.selected[$index] In this way, you can bind different v-models to different inputs to operate them separately. In the demodataBind.vueUsed in.

12. Transition animation in vuejs

In vuejs, css defines the animation:

 .zoom-transition{  width:60%;  height:auto;  position: absolute;  left:50%;  top:50%;  transform: translate(-50%,-50%);  -webkit-transition: all .3s ease;  transition: all .3s ease; } .zoom-enter, .zoom-leave{  width:150px;  height:auto;  position: absolute;  left:20px;  top:20px;  transform: translate(0,0); }

When setting an animation, pay attention to the upper-right correspondence. There is something on it, and there is something to change. If there is no change, it should be pulled out as a public css style, in the above css, if I only write transform: translate(-50%,-50%);Without writing the followingtransform: translate(0,0);This will cause the abovetransform: translate(-50%,-50%);Is added to the following, it is considered unchanged.

XIII. Use of command v-el

Sometimes we want to access an element just like using jquery. In this case, we can use the v-el command to register an index for this element, you can easily access this element through $ el of the instance.

Note:

HTML is case insensitive, sov-el:someElConverts to lowercase letters. Availablev-el:some-elThen setthis.$el.someEl.

Example

<span v-el:msg>hello</span><span v-el:other-msg>world</span>this.$els.msg.textContent // -> "hello"this.$els.otherMsg.textContent // -> "world"this.$els.msg //-><span>hello</span>

14. Use event names in vuejs

In vuejs, we often need to bind events, sometimes to DOM elements, and sometimes to components. Bind events in HTMLv-on:click-"event"In this case, the evet name should not contain uppercase letters, because it is case-insensitive in 1.x, so if we writev-on:click="myEvent"An error occurs when writing myEvent in js. Therefore, avoid using uppercase letters when binding Event 1. x in vuejs. This restriction is not found in 2.0!

Differences between v-if and v-show

V-if directly does not render this DOM element, while v-show will render the DOM element. It only uses display: none to hide it. Open the developer tool and you can see the DOM.

16. How to Use the transition global hook in components

Vue.transitionIs to define a global transition hook, if you want to define for components, you need to write the following code:

export default{ transition:{  'fade':{   enter() {},   leave() {}  } }}

In this way, the excessive fade hook only acts on the component. If a global hook with the same name exists at the same time, the build-up defined

17. How to Use vue-router to execute an event before rendering the component

Export default {data () {return {selected: 0, currentView: 'view _ 0' }}, methods: {choose (index) {this. selected = index; this. currentView = 'view _ '+ index ;}, route: {data () {/* each time the route is switched, It will be executed before the page is rendered */}}}

Summary

The above is all the summary of the use of vue. js. I hope this article will help you learn or use vue. js. If you have any questions, please leave a message.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.