preface

This is my 35th day with the Nuggets

Start learning Vue3 again this month, from understanding basic usage to simulation implementation!

Related articles in this series are as follows:

The base class

  1. Understand the application examples and component instance | relearn Vue3
  2. Understand the template syntax | relearn Vue3
  3. Deep understanding of the data and the methods of configuration options | relearn Vue3

Handwriting implementation class

  1. Simulate the Vue3 initialization process
  2. Simulate implementation of all Vue3 responsive APIS (1)

This is the sixth article on the configuration options in Vue: compute properties and listeners

Look at the text and you will have a clear idea of the two options

The directory structure is as follows:

Calculate attribute

This punishment 3 small points:

1. What are computed attributes

The compute property is one of the configuration options for the component: computed

{
  / /...
  computed:{}
}
Copy the code

It is essentially an object that contains a set of properties whose values can be methods or objects

  computed: {
    / / method
    sum(){
      / /...
    },
    / / object
    average: {
        // getter
        get() {
          / /...
        },
        // setter
        set(newValue) {
            / /...}}}Copy the code

2. What does it do

In a template, we usually want the expression to be short and easy to read, but sometimes the expression can become complicated. Complicated expressions can make the template complex and difficult to maintain. The following shows the students’ total score and even score:

<template>
  <table border="1">
      <thead>
          <th>discipline</th>
          <th>score</th>
      </thead>
      <tbody>
          <tr>
              <td>Chinese language and literature</td>
              <td><input type="text" v-model="Chinese"></td>
          </tr>
          <tr>
              <td>mathematics</td>
              <td><input type="text" v-model="math"></td>
          </tr>
          <tr>
              <td>English</td>
              <td><input type="text" v-model="English"></td>
          </tr>           
          <tr>
              <td>Total score</td>
              <td>{{math + English + Chinese}}</td>
          </tr>
          <tr>
              <td>average</td>
              <td>{{(math + English + Chinese)/3}}</td>
          </tr>
      </tbody>
  </table>
</template>

<script>
export default {
  data() {
    return {
      math: 88.English: 77.Chinese: 99,}}}</script>
Copy the code

In the above code, although the final result can be shown, the inside of {{}} becomes very unclear, especially when the operations are more complex, and the code is too big. What if?

You might think of methods

So can methods! However, it is better to use computed attributes because they not only solve the above problems, but also have a caching effect, which improves performance by calling previously cached data when the dependent data has not changed

So I can modify the example above and add the computed property

computed: {
    sum() {
        console.log('Calculated property: sum called');
        return this.math + this.English + this.Chinese;
    },
    average() {
        console.log('Called calculated property: average');
        return Math.round(this.sum / 3); }}Copy the code

So the template becomes clear

<tr>
  <td>Total score</td>
  <td>{{sum}}</td>
</tr>
<tr>
  <td>average</td>
  <td>{{average}}</td>
</tr>
Copy the code

And when called multiple times, as long as the dependency has not changed, it will not be counted twice, that is, the cached data is called

Score < tr > < td > < / td > < td > {{sum}} < / td > < / tr > < tr > < td > total score < / td > < td > {{sum}} < / td > < / tr >Copy the code

The results are as follows

You can see that sum is actually only called once

3. Suggest

The use of computed properties is recommended for any expression that contains complex logic with responsive data

The listener

This punishment 3 small points:

1. What is a listener

The listener Watch, like computed, is one of the component configuration options

{
    data() {
        return {
          count:1}},watch: {
        / /...}}Copy the code

It is essentially an object that contains a series of methods whose method names correspond to the names of the properties to be listened on

watch: {
    count(){... },/ /...
}
Copy the code

2. What does it do

You can use it to customize listeners that listen for the responsive data you want to listen for.

<template>
  <h1>{{ count }}</h1>
</template>

<script>
export default {
  name: "HelloWorld".data() {
    return {
      count: 0}},watch: {count(val){
      console.log('Listener count executed'); }},mounted(){
    this.count ++
  }
}
</script>
Copy the code

This is especially useful when asynchronous or expensive operations need to be performed as data changes

Take this example from the website:

<div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question" />
  </p>
  <p>{{ answer }}</p>
</div>
Copy the code
<! Because the ecology of AJAX libraries and common tools is already rich, Vue core code is not duplicated -->
<! -- Provide these features to keep things lean. It also gives you the freedom to choose the tools you're more familiar with. -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
<script>
  const watchExampleVM = Vue.createApp({
    data() {
      return {
        question: ' '.answer: 'Questions usually contain a question mark. ; -) '}},watch: {
      // whenever question changes, this function will run
      question(newQuestion, oldQuestion) {
        if (newQuestion.indexOf('? ') > -1) {
          this.getAnswer()
        }
      }
    },
    methods: {
      getAnswer() {
        this.answer = 'Thinking... '
        axios
          .get('https://yesno.wtf/api')
          .then(response= > {
            this.answer = response.data.answer
          })
          .catch(error= > {
            this.answer = 'Error! Could not reach the API. ' + error
          })
      }
    }
  }).mount('#watch-example')
</script>
Copy the code

3. $watch

Vue has the $watch property built into the component instance, which is used to listen for properties just like the watch configuration option

conclusion

To make it easier to view, I’ve distilled everything into one image

END~

That’s all for configuring the options Computed and Watch

If you have any questions, please leave a message. Thank you