Usage scenarios

Let’s assume a text in a component with the content 123,456,789

<template>
    <div class="demo">
        {{text}}
    </div>
</template>

<script>
    export default {
      data(){
        return{
          text:"123456789",}}}</script>
Copy the code

Now I want to change the page to 789,456,123. How do I do that? {{}}, for example:

// Convert a string to an array by reversing the order of the array to a string
 {{text.split(",").reverse(),join(",")}}
Copy the code

You can get the effect you want.

But if I had to add more operations, the expression would have become very long, unsightly, and unreadable.

To solve this problem, consider using:

  1. Use computed- To compute attributes.
<template>
    <div class="demo">
        {{reverseText}}
    </div>
</template>

<script lang='js'>
    export default {
      data(){
        return{
          text:"123456789",}},computed: {
        reverseText: function(){
          return this.text.split(', ').reverse().join(', ')}}}Copy the code

Pull out all the computed steps and put them in a computed property on the same level as data, so the output of the page is 789,456,123.

  1. Use method- method
<template>
    <div class="demo">
        {{reverse()}}
    </div>
</template>

<script lang='js'>
  export default {
    data() {
      return {
        text: "123456789",}},methods: {
      reverse() {
        return this.text.split(', ').reverse().join(', ')}}}</script>
Copy the code

Define a reverse method and write the calculation steps into the method. Just call the reverse method in {{}} and get 789,456,123.

Key differences between computed properties and methods

  • The result of evaluating a property is a property that can be written directly into {{}}, while a method is a function that requires a () to be called.

  • Computed properties are based on its dependency cache. In the example above, the computed property is updated only when the data text on which the computed property depends changes, and when the user accesses reverseText multiple times, it immediately returns the computed result without needing to perform it again. The method, which executes the function again every time a page triggers a re-rendering, is more performance-efficient than computed property, so the longer and more complex the data requires, the more you should stick with computed property.