Vue Official Document Notes

Posted by kath421 on Mon, 30 Sep 2019 15:00:48 +0200

1. How to create a Vue instance object?

var vm = new Vue({
          el: "#app",  //Label id Or label class name
          data:{ //Bidirectionally bound data
              message: "Wang Da hammer",
              show: true,
              arr: [
                  { name: "Wang Da hammer", age: 18 }, { name:"Luo Xiao Hu", age: 19 }
              ]
          }
      })

When a Vue instance (such as the vm above) is created, it adds all the attributes in the data object to the Vue response system. When the values of these attributes change, the view generates a "response", that is, the view displays the latest data.

How to bind data bidirectionally? Binding data with v-model, such as:

<input v-model="message" />

 

2. How to realize if else? Use v-if, v-else, v-else-if, for example:

<div v-if="show">show by true Exhibition</div>
<div v-else>show by false Exhibition</div>

3. How to use the for loop?

  • Without index, format: V-for = item in arr, e.g.
    <div v-for="item in arr">{{item.name}}---{{item.age}}</div>
  • With index, format: v-for="(item, index) in arr", such as:
    <div v-for="(item, index) in arr">{{index}}--{{item.name}}</div>
  • In addition to traversing arrays, for loops can also traverse objects, traversing their attributes in the form of V-for = value in object / V-for = value, name in object / V-for = value, name in object

 

4. After the Vue instance is created, all the attributes in the data object will be added to the responding system. When the values of these attributes change, the view will generate a "response". If you don't want to be tracked by the responding system, how to operate?

Object.freeze() method is used to process data that you do not want to be tracked.

 

5. How do you know which tag the current Vue instance object is working on?

The Vue instance. el is the target tag, such as vm.el == document.getElementById("#app"). In the example, this.$el also points to the target tag.

 

6. If the attribute values in data in the Vue instance change, we want to know in time, how to do it?

In the watch method, the attributes are monitored so that when the value of the attributes changes, the watch will know in time. For example, you want to listen for changes in the value of the message attribute in data.

//The first way
vm.$watch('message', function(newValue, oldValue){
    //This callback function will be 'vm.message' Call after change
})
//The second way is in Vue Write in the example
      new Vue({
          el: "#app",
          data: {
              message: "hello",
              //...
          },
          watch: {
              message: function(newValue, oldValue){
                //This callback function will be'message'Call after change
              }
          }
      })

 

7, why not use arrow function in option attribute or callback of Vue instance?
For example, it is similar to create: () =>{console. log (this. message)}, or vm. $watch ('a', newValue => this. myMethod ().

Because there is no this in the arrow function, if you use the arrow function, then the arrow function uses this again. In order to find this, when this is not found in the current arrow function, the system will always look up the upper lexical scope until it is found, so it often leads to errors such as Uncaught TypeError: Cannot read property of undefined or Uncaught TypeErrorr: this.myMethod is not a function.

 

8. What process has a Vue instance gone through from creation to destruction? What is its life cycle?

There are eight main steps

8.1 beforeCreate: Create a Vue instance, initialize the event of the instance, injections (injection: usually check whether there is a parent signal injection, where you can receive references to parent components or attributes, in conjunction with the provider attributes provided by the parent), reactivity (reactivity: Initialization of methods to monitor attribute changes, such as watch).

8.2 Create: When an instance enters create, it is judged whether it contains an "el" option. If not, it calls the vm.$mount(el) method and executes the next step; if it does, it executes the next step directly. The next step is to determine whether the "template" option is included, and if so, it resolves the template into a render function.

8.3 BeforeMount: In the beforeMount stage, render is completed, vm.$el is created, and the rendered content is mounted on the DOM node.

8.4 Mounted: In mounted stage, data request - > Data Update - > and view re-rendering - > data change - > re-rendering and so on. This process of changing data actually includes two periodic functions, beforeUpdate and update.

8.5 beforeDestroy: When the Vue instance needs to be destroyed, the beforeDestroy function is executed, and then the attribute listener (watch), subcomponents, event listener (method) and so on are disassembled here.

8.6 the last step of destroyed: is to destroy Vue instance and complete its great achievement.

This is an official life cycle chart:

9. What is the directive of v-once and what is the use?

One-time interpolation and adding the v-once attribute to the html tag indicate that the bound text interpolation in the tag will only show the data loaded for the first time. If that data changes later, the contents of this tag will not be updated.

 

10. How to operate if text interpolation is converted to html tags (converting bound data to html tags)?

Use v-html attributes such as: <div v-html="customHtml"></div>

Note: Dynamic rendering of arbitrary HTML can be very dangerous because it can easily lead to XSS attacks. Please use HTML interpolation only for trusted content, never for user-provided content.

  

11. For interpolation in HTML tags, use double brackets {message} to bind data. If you want to bind data to attributes in HTML tags, such as class name (.), style, custom attributes, how to operate?

The general format is v-bind: attribute name = "variable name", such as:

<div v-bind:class="myClass" v-bind:style="myStyle" v-bind:key="myKey"></div>

The format of the binding event is v-on: event type = "event name", such as:

<input  v-on:click="showMsg"   v-on:focus="getFocus"   v-on:blur="getBlur" />

 

12. For some of the existing form tags, that is, true attributes, how to make them default to false (such as checked attributes of check box, disabled attributes of all form tags)?

For example:

<input type="checkbox" checked/> 
<input type="checkbox" checked="true" /> 
<input type="checkbox" checked="false"/>

The effect of these three methods is the same, that is, when these checkboxes are rendered, they default to the selected state, and similar disabled attributes are the same.

How to make them false by default? Using v-bind, for example:

<input type="checkbox" v-bind:checked="false"/> 
<input v-bind:disabled="false"/>

 

13. In addition to binding variables, Vue template grammar can also bind expressions, such as:

<div>{{number + 1}} , {{ok ? 'Exhibition':'hide'}} ,{{message.split('').reverse().join('')}}</div>

 

14. The abbreviations of v-bind and v-on:

v-bind: It can be abbreviated as:

<div v-bind:href="url" v-bind:class="myClass"></div>

It can be abbreviated as

<div :href="url" :class="myClass"></div>

v-on: Can be abbreviated as@

<input  v-on:focus="getFocus" v-on:click="clickMe"/>

It can be abbreviated as

<input @focus="getFocus" @click="clickMe"/>

 

15, the expression in the template can carry out simple operations. What are the consequences if complex logic is carried out in the template? What alternatives do we have?

Placing too much logic in the template can make the template overweight and difficult to maintain. Therefore, computational attributes should be used for any complex logic. Such as:

<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    // Computing attributes getter
    reversedMessage: function () {
      // `this` point vm Example
      return this.message.split('').reverse().join('')
    }
  }
})

We can bind computational attributes in templates just like ordinary attributes, which have established dependencies. When common attributes change, computational attributes are updated as well.

Of course, we can see that the use of computational attributes can achieve the same effect, such as:

<p>Reversed message: "{{ reversedMessage() }}"</p>
var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  methods: {
      reversedMessage: function () {
        return this.message.split('').reverse().join('')
      }
    }
})    

So the question arises, since the effect of using computational attributes and methods is the same, which one is better or better?

This should be analyzed in detail to see which scenarios are used. Computational attributes are cached based on their responding dependencies, and they are revalued only when the relevant responding dependencies change. This means that as long as the message hasn't changed, multiple access to the reversedMessage computational property will immediately return the previous calculation result without having to execute the function again. In contrast, whenever a re-rendering is triggered, the calling method always executes the function again.

Therefore, according to the actual need for caching, to determine whether the use of computational attributes, or the use of methods, so that higher performance.

In addition, comparing the differences between computed attributes vs listening attributes, it is usually better to use computed attributes rather than imperative watch callbacks when some data needs to change with other data. Such as:

  

<div id="demo">{{ fullName }}</div>
var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})

The above code repeats imperatively. And see how this effect can be achieved by using computational attributes:

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})

You can see that in this scenario, using computational attributes is much better than listening attributes.

 

16. How many ways to bind class names and inline styles to tags?

There are two main types: object grammar and array grammar.

<div :class="{classOne: classObj.isOK, 'classTwo': classObj.isNO}">class Object Grammar</div>
<div :class="{'classOne': classObj.isNo, 'classTwo': classObj.isOK}">class Object Grammar</div>
<div class="classZero" :class="classObj2">class Object Grammar</div>
<div :class="classObj3">class Array grammar</div>
<div :class="[classObj3[0], classObj3[1]]">class Array grammar</div>
<div :style="{fontSize: styleObj.fontSize, border: styleObj['border-bottom']}">style Object Grammar</div>
<div :style="styleObj">style Object Grammar</div>
<div :style="[styleObj, styleObj2]">style Array grammar</div>
data:{
    classObj: { isOK: true, isNO: false }, //class Object syntax
    classObj2: { classOne: true, classTwo: true }, //class Object Grammar 2
    classObj3: ['classOne', 'classTwo'],   //class Array grammar
    styleObj: { fontSize: '50px', 'border-bottom': '8px dashed purple', color: 'red' }, //Inline Style Object Grammar
    styleObj2: { borderLeft: '3px solid red', 'border-right':'5px solid green' }, //Inline Style Object Grammar
},

Finally, the eight div s are rendered as follows:

<div class="classOne">class Object Grammar</div>
<div class="classTwo">class Object Grammar</div>
<div class="classZero classOne classTwo">class Object Grammar</div>
<div class="classOne classTwo">class Array grammar</div>
<div class="classOne classTwo">class Array grammar</div>
<div style="font-size: 50px; border: 8px dashed purple; ">style Object Grammar</div>
<div style="font-size: 50px; border-bottom: 8px dashed purple; color: red">style Object Grammar</div>
<div style="font-size: 50px; border-bottom: 8px dashed purple; color: red; border-left: 3px solid red; border-right: 5px solid green;">style Array grammar</div>

Topics: Javascript Vue Attribute