Vue computed with parameters (computed properties)

In official cases, computerd has no attributes.

<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: {
    
    
    // 计算属性的 getter
    reversedMessage: function () {
    
    
      // `this` 指向 vm 实例
      return this.message.split('').reverse().join('')
    }
  }
})

If reversedMessage is changed to a form with parameters.

reversedMessage: function (parameter) 

Then when using it, an error will be reported: reversedMessage is not a function.
This is because the return value is string.

So if you want to have parameters, you need to modify the reversedMessage slightly.

 <p>Computed reversed message: "{
    
    { reversedMessage('2333') }}"</p>
 reversedMessage: function () {
    
    
      // `this` 指向 vm 实例
      return (parameter)=>{
    
    
   	   return  this.message.split('').reverse().join('') + parameter
	 } 
    }

In this way, the return value of reversedMessage is an anonymous function, and this function will complete the result originally calculated by reversedMessage.
It is worth noting that if parameter is placed after the attribute to be calculated, the vm instance will be obtained.

reversedMessage: function (parameter) {
    
    
// parameter == vm
}

Guess you like

Origin blog.csdn.net/qq_42988836/article/details/106542901