vue deeply understands v-bind instruction

Keywords: Javascript

Introduction to v-bind

<span :text="content">Use</span>

It renders as follows:

<span text="content">Use</span>

String splicing

<span :text=' "we" + 1 '>Use</span>

It renders as:

<span text='we1'>Use</span>

Therefore, to use string splicing in the v-bind instruction, you only need to combine quotation marks.

operation

<div :text='1 + 2'>test</div>

Render to:

<div text="3">test</div>

Calling function

 <div :text='getText()'>test</div>
 ......
 <script>
export default {
  methods: {
    getText() {
      return "this is text"
    }
  }
}
</script>

Render to:

<div text="this is text">test</div>

Use object

New object:

<template>
  <div class="hello">
    <div :text='obj'>test</div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      obj: Object()
    }
  }
}
</script>

The result is:

<div text="[object Object]">test</div>

If the object has a toString method:

<template>
  <div class="hello">
    <div :text='obj'>test</div>
  </div>
</template>

<script>
var obj = Object()
obj.toString = function(){
  return "data in obj"
}
export default {
  name: 'HelloWorld',
  data () {
    return {
      obj: obj
    }
  }
}
</script>

Then the value of toString method is rendered:

<div text="data in obj">test</div>

Using arrays

<template>
  <div class="hello">
    <div :text='array'>test</div>
  </div>
</template>

<script>
var array = Array()
array[0] = "1"
array[1] = "2"
export default {
  name: 'HelloWorld',
  data () {
    return {
      array: array
    }
  }
}
</script>

Render as:

<div text="1,2">test</div>

The same value as toString

v-bind vs calculation properties

<template>
  <div class="hello">
    <div :text='myText'>test</div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      value: "data"
    }
  },
  computed: {
    myText: function(){
      return "value is " + this.value
    }
  }
}
</script>

By comparison, it is not difficult to find that the computing properties are the same as the above functions, but in the case of string splicing, the advantage of using the computing properties is that they are separated and do not write logic in html. So calculating properties is a more recommended use.

conclusion

To sum up, in the v-bind instruction, legal javascript expressions are used. Based on this principle, it will not be much difficult to write the v-bind instruction in the future.

Posted by rogair on Wed, 08 Jan 2020 10:00:48 -0800