Computed computing properties and watch listening properties

computed: depends on responsive dependent data, when responsive dependentchangewhen,change by itself, if the responsive dependency has not changed, the values ​​returned subsequently will be the previous ones and will not be recalculated. Defined computed property names can be used directly like variables declared in data. Multiple reactive dependencies can be listened to within a computed property function.

watch: Listens to changes in its own responsive dependent data, and triggers the defined function content when it changes. Can be inside listener functionexecute asynchronouslyorexpensive operationsas well asset intermediate state, but a listen function only listens to a reactive dependency and does not generate new variable names.

computed

Using expressions in templates is very convenient, but they are designed forsimple operationof. Putting too much logic in templates can make them heavy and difficult to maintain. For example:

<div id="example">
  {
    
    {
    
     message.split('').reverse().join('') }}
</div>

In this place, templates are no longer simple declarative logic. You have to look at it for a while to realize that here is the flipped string that wants to display the variable message. It gets even more tricky when you want to include this flipped string in multiple places in your template.

So in order to keep the code clean and readable, you should use computed properties for any complex logic.

And reversedMessage is dependent onResponsive dependency messageYes, when the message changes, the reversedMessage will also change accordingly.

<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('')
    }
  }
})

Similarly, we can achieve the same effect by calling methods in expressions:

<p>Reversed message: "{
    
    { reversedMessage() }}"</p>

methods: {
    
    
  reversedMessage: function () {
    
    
    return this.message.split('').reverse().join('')
  }
}

the difference iscomputed propertyare based on theirResponsive dependencies for cachingof. They only fire when the relevant reactive dependencies changere-evaluate. This means that as long as the message has not changed, accessing the reversedMessage computed property multiple times will immediatelyReturns the previous calculation result, without having to execute the function again.
In contrast, whenever a re-render is triggered,Calling a method will always execute the function again

This also means that the following computed properties will no longer update, since Date.now() is not a reactive dependency:

computed: {
    
    
  now: function () {
    
    
    return Date.now()
  }
}

watch

When the data needs to changeexecute asynchronouslyorhigh costIt is most useful to use the watch method for the operation.

<div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question">
  </p>
  <p>{
   
   { answer }}</p>
</div>
var watchExampleVM = new Vue({
    
    
  el: '#watch-example',
  data: {
    
    
    question: '',
    answer: 'I cannot give you an answer until you ask a question!'
  },
  watch: {
    
    
    // 如果 `question` 发生改变,这个函数就会运行
    question: function (newQuestion, oldQuestion) {
    
    
      this.answer = 'Waiting for you to stop typing...'
      this.debouncedGetAnswer()
    }
  },
  created: function () {
    
    
    // `_.debounce` 是一个通过 Lodash 限制操作频率的函数。
    // 在这个例子中,我们希望限制访问 yesno.wtf/api 的频率
    // AJAX 请求直到用户输入完毕才会发出。想要了解更多关于
    // `_.debounce` 函数 (及其近亲 `_.throttle`) 的知识,
    // 请参考:https://lodash.com/docs#debounce
    this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
  },
  methods: {
    
    
    getAnswer: function () {
    
    
      if (this.question.indexOf('?') === -1) {
    
    
        this.answer = 'Questions usually contain a question mark. ;-)'
        return
      }
      this.answer = 'Thinking...'
      var vm = this
      axios.get('https://yesno.wtf/api')
        .then(function (response) {
    
    
          vm.answer = _.capitalize(response.data.answer)
        })
        .catch(function (error) {
    
    
          vm.answer = 'Error! Could not reach the API. ' + error
        })
    }
  }
})

In this example, using the watch option allows us toperform an asynchronous operation(accessing an API), limit how often we can do that, and before we get the final result,set intermediate state. These are things that computed properties cannot do.

Guess you like

Origin blog.csdn.net/qq_45488467/article/details/127979968