Understanding and thinking about vue. js v-bind, vue. jsv-bind

Source: Internet
Author: User

Understanding and thinking about vue. js v-bind, vue. jsv-bind

I. v-bind

It is a vue command used to bind html attributes, as follows:

<Div id = "app"> <p v-bind: title = "title"> html attributes cannot be bound in double braces, only the v-bind command can be used </p> </div> ...... var vm = new Vue ({el: '# app', data: {title: 'title content '}});

The html will be rendered as follows:

<Div id = "app"> <p title = "title content"> html attributes cannot be bound in double braces. Only the v-bind command can be used. </p> </div>

Ii. Pre-instruction value

The above v-bind is our initial understanding of the vue command, but in fact, the pre-period value of the vue command (such as v-bind: class = "classProperty, v-bind is the command, and the class behind it is the parameter, while classProperty is called the "Expected Value" in the official documentation). Apart from binding a string type variable as above, in fact, it supports a single JavaScript expression (except for v-).
So here we can have more options, such:

(1) execute operations

<Div id = "app"> <p v-bind: title = "t1 +'' + t2 "> html attributes cannot be bound in double braces, only the v-bind command can be used </p> </div> ...... var vm = new Vue ({el: '# app', data: {t1: 'title1', t2: 'title2 '}});

Final rendering result:

<Div id = "app"> <p title = "title1 title2"> html attributes cannot be bound in double braces. Only the v-bind command can be used. </p> </div>

(2) execute functions

<Div id = "app"> <p v-bind: title = "getTitle ()"> html attributes cannot be bound in double braces, only the v-bind command can be used </p> </div> ...... var vm = new Vue ({el: '# app', data: {getTitle: function () {return 'title content ';}}});

Final rendering result:

<Div id = "app"> <p title = "title content"> html attributes cannot be bound in double braces. Only the v-bind command can be used. </p> </div>

Iii. supported data types

In the above content, the directive's expected values are all string-type data, but we actually know that js has many data types. What if it is put in it?

(1) object type

<div id="app">  <p v-bind:title="obj">content</p></div>......var obj = {};var vm = new Vue({  el: '#app',  data: {    obj: obj  }});

Why select an object type? The answer is that it is representative, and the rendering result is as follows:

<div id="app">  <p title="[object Object]">content</p></div>

Ah, how can this be a bit familiar? A bit like... that's right! The Return Value of the toString method of the object! To verify our conjecture, we conduct further tests:

<div id="app">  <p v-bind:title="obj">content</p></div>......var obj = {};obj.toString = function () {  return 'edited in toString!';};var vm = new Vue({  el: '#app',  data: {    obj: obj  }});

The toString method of obj is modified here (but to be precise, it is not modified but added here. At the beginning, the obj Object itself does not have the toString method, and it inherits the Object. prototype. toString, but here we execute obj. toString = function ..... in fact, A toString method is added for it so that it does not need to call the method inherited from the Object when it is executed. The rendering result is as follows:

<div id="app">  <p title="edited in toString!">content</p></div>

Here We further confirm our conjecture.

(2) array type

The toString method of the array type is different from the object type. It returns the same result as the execution of arr. join. For example, [1, 2, 3]. toString () will return "1, 2, 3 ". Perform the following tests:

<div id="app">  <p v-bind:title="arr">content</p></div>......var vm = new Vue({  el: '#app',  data: {    arr: [1, 2, 3]  }});

The rendering result is as follows:

<div id="app">  <p title="1,2,3">content</p></div>

The results are still the same as expected.

(3) Other types

  1. Number type. The toString is executed normally, including the number 0. The result is rendered as the corresponding string;
  2. Boolean type. true is normally rendered as a string "true", but false is not rendered even if the toString method is executed to return the "false" string;
  3. Null/undefined type. The two are neither added nor rendered using the toString method.

Obviously, before the toString method is executed, the vue should first perform type verification to output the data only when the conditions are met. In addition, this is not a simple verification of true/false values, because 0 is a false value, but it is rendered as a true value. For details about how to implement it, you may need to refer to the source code of vue.

4. Bind Multiple html attribute valuesSet

An html attribute value may contain a lot of content. We need to perform some operations to bind multiple data to one attribute. Here we can consider the same as before, use operators such as "+" to connect strings. But in fact, string connection is troublesome and error-prone, and is not easy to maintain. Therefore, we can consider saving an object or array to the pre-period value of the instruction as before to bind multiple data to one attribute.

(1) binding with objects

<Div id = "app"> <p v-bind: title = "obj"> content </p> </div> ...... var obj = {name: 'dale ', age: 22}; // uses the for-in loop to traverse object attributes and splice them into a string obj. toString = function () {var str = ''; for (var I in this) {str + = I + ':' + this [I] + ';';} return str ;}; // prevent the toString method from traversing the Object itself. defineProperty (obj, 'tostring', {'enumerable': false}); var vm = new Vue ({el: '# app', data: {obj: obj }});

Output result:

<div id="app">  <p title="name: Dale; age: 22; ">content</p></div>

The above uses the for-in loop to obtain all the attributes that can be traversed and the corresponding attribute values in the toString method, and then concatenates them into strings for output. This can bind multiple attribute values. As for how to splice them, you can perform different implementations in the toString method.

(2) bind an array

<div id="app">  <p v-bind:title="arr">content</p></div>......var arr = [1, 2, 3];arr.toString = function () {  return this.join(' ');};var vm = new Vue({  el: '#app',  data: {    arr: arr  }});

The rendering result is as follows:

<div id="app">  <p title="1 2 3">content</p></div>

Compared with object String concatenation, array concatenation is much simpler. the return value of the join method can be directly returned in the toString method. The return value of the default toString method is actually the same as that of the join (',.

(3) Thinking

In fact, it is not uncommon to bind an html attribute to multiple values. The most typical case is the class and style attributes, or we often come into contact with such scenarios.

However, the implementation here seems to be a lot of problems, the array binding is good, the object binding, in addition to every rewrite toString method, we also need to set toString method to become not enumerative, otherwise, it will be traversed in the for-in loop (in general, this is not the result we want to see), which will undoubtedly increase a lot of repetitive work, vue has taken this into consideration, and it has performed some optimization operations within the framework.

V. Enhancement of vue binding class and style

Based on the above situation, vue enhances the html attributes of class and style to a certain extent. For more information about the vue implementation method, see the source code. Here we only provide the implementation method based on the above conclusions.

(1) object-based class Enhancement

<Div id = "app"> <p v-bind: class = "obj"> content </p> </div> ...... var obj = {c1: true, c2: false, c3: null, c4: undefined}; obj. toString = function () {var str = ''; for (var I in this) {if (this [I]) {str + = I + '';}} return str ;}; // prevent the toString method from traversing the Object itself. defineProperty (obj, 'tostring', {'enumerable': false}); var vm = new Vue ({el: '# app', data: {obj: obj }});

Rendering result:

<div id="app">  <p class="c1">content</p></div>

The same is for-in. different from the previous one, when a property value of obj is detected to be true, the attribute name of this property is added to the Bound Element class. Of course, here I am just a simulated implementation. For the actual implementation method of vue, see vue source code.

(2) array-based class Enhancement

<div id="app">  <p v-bind:class="arr">content</p></div>.......var arr = ['c1', 'c2', 'c3'];arr.toString = function () {  return this.join(' ');};var vm = new Vue({  el: '#app',  data: {    arr: arr  }});

Rendering result:

<div id="app">  <p class="c1 c2 c3">content</p></div>

Here, we basically use join ('') as the previous implementation method.

(3) Enhance the style based on objects

<Div id = "app"> <p v-bind: style = "obj"> content </p> </div> ...... var obj = {color: 'red', backgroundColor: '# ddd', fontSize: '20px ',}; obj. toString = function () {var str = ''; for (var I in this) {if (this [I]) {str + = I + ': '+ this [I] +'; ';}} return str ;}; // prevents the toString method from traversing the Object itself. defineProperty (obj, 'tostring', {'enumerable': false}); var vm = new Vue ({el: '# app', data: {obj: obj }});

Rendering result:

<div id="app">  <p style="color: red; background-color: rgb(221, 221, 221); font-size: 20px;">content</p></div>

This is basically the same as the previous implementation idea. It is implemented using for-in and String concatenation.

(4) array-based style Enhancement

<div id="app">  <p v-bind:style="arr">content</p></div><script>var arr = [{    color: "red"  }, {    backgroundColor: '#ddd'  }, {    fontSize: '20px'  }];arr.toString = function () {  var str = '';  arr.forEach(function (val, key) {    for(var i in val) {      str += i + ':' + val[i] + ';';    }  });};var vm = new Vue({  el: '#app',  data: {    arr: arr  }});

Rendering result:

<div id="app">  <p style="color: red; background-color: rgb(221, 221, 221); font-size: 20px;">content</p></div>

Here, the forEach method is used to traverse the array, and then the array elements (that is, the style object here) are traversed through for-in and spliced into a style string to achieve the effect.

Vi. Conclusion

Once again, this is just my personal understanding and thinking. It is for your reference only. The vue implementation methods may not be the same.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.