The articles I’ve written lately are probably the kind of long, dry stuff that scares me at length… . So in this article, let’s talk about something light and practical, about computed parameter transmission

As always, look at the problem first!

  • Does little White Vue know that computed ginseng is used? ! ๐Ÿ‘‡
  • Old Vue does not understand the principle of parameter transmission, so every time I use computed parameter transmission, I have to search for information. ! ๐Ÿ‘‡
  • Old and new Vue don’t know that computed has been removedgetThere areset? ! ๐Ÿ‘‡

Ok! If you have such pain points, keep reading. This article takes a look at the source code for computed parameter transfer! (If you understand this, make sure you don’t need Baidu for writing computed parameters!) Let me show you how to play with computed SET ~ ๐Ÿ˜Ž

Tips: If you still want to learn more about how computed works, you can click here to see the Easter eggs section of this article, full of dry stuff that takes you deep into computed source code implementation!

1. Three methods for computed Tomography

So let’s look first at all the different ways that we have computed

  1. In normal function writing, a callback returns a value
  2. In higher-order function writing, a callback returns a function that accepts arguments.
  3. Object writing, object writing must provide get method, of course, can also set method
<template>
  <div id="app">
    <p>Conventional computed notation: {{wholeName1}}</p>
    <p>Computed Data transmission: {{wholeName2(' Boran ')}}</p>
    <p>For computed GET: {{wholeName3}}</p>
  </div>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
      firstName: 'well'.secondName: 'BaiRan'}},computed: {
    wholeName1 () {
      return  this.firstName + this.secondName
    },
    wholeName2 () {
      return secondName= > this.firstName + secondName
    },
    wholeName3: {
      get () {
        return this.firstName + this.secondName
      }
    }
  }
}
</script>
Copy the code
  • As shown, awesome! ๐Ÿ‘‡

Visible, three writing methods can achieve our expected output ~ do not know how you usually use them to solve various business problems ๐Ÿ˜œ


Ii. How to play with computed ginseng transmission?

1. Scenarios for computed parameter transmission

So even though we’re talking about ginseng transfer, the first thing we should think about is, why do we use computed ginseng transfer? What problem does parameter passing solve?

  • Handles concatenation of strings
    1. Write directly in template:{{ msg1 + default1 + default2 + default... }}
    2. Using the computed to:{{ wholeMsg(msg1) }}
  • Processing data, such as need to presentThe percentageThe back end only returns0.xx
    1. Write directly in the template:{{ pointNumber * 100 + '%' }}
    2. Using the computed to:{{ percent(pointNumber) }}
  • Crazy ultra-deep data?
    1. Write directly in the template:{{ obj.a.b.c.d.e.f.g...... name }}
    2. Using the computed to:{{ getName(obj) }}
  • Table The label for a column to display a list, and the back end only gives a key?
  • Sum up in one sentence and write onefunction.receiveA raw value,returnA processed value to address the requirements of various business scenarios!

You also don’t say, for often walk in the B end of FE, these are really just commonplace, there are all kinds of strange scenes are not a repeat of ๐Ÿคจ… .

After a simple example, have you found:

  1. Can using computed writing make templates cleaner?
  2. Is the readability better than the various concatenations written directly on the template?
  3. Implementation of the common code to pull out, components everywhere directly a function to receive a parameter is done?

So ๐Ÿ‘‰, using computed data transfer flexibly can solve many problems in our daily development and make your development more convenient

2.computed How to write a reference?

Review the nature of computed implementation. Therefore, for computed objects, Object. DefineProperty is a hijacking. When we access the computed property in the template (the compiled render function), the getter for computed ~! Then it calls the cb method that we wrote computed

๐Ÿ˜œ extra: If you want to learn more about computed computations, click on the link above at ๐Ÿ‘† to see the Easter egg chapter

Before the case study of computed parameter transmission, first introduce the concept of higher-order functions:

  • A higher-order function is a function that takes a function as an argument or returns a function as output
  • As an example, we often use loading or catch errors to initiate an asynchronous request.
    1. Handled separately in each business method, as shown in the following code block
    const fetch1 = async() = > {try {
            this.loading = true
            const result = await postFunction(data)
            ...
        } catch (e) {
            console.error('Error capture', e)
        } finally{
            this.loading = false}}const fetch2 = async() = > {try {
            this.loading = true
            const result = await getFunction(params)
            ...
        } catch (e) {
             console.error('Error capture', e)
        } finally{
            this.loading = false}}Copy the code
    1. Wrapped in higher-order functions, unified processing returns the business method
    const loadingAndCatch = cb= > {
        return async() = > {try {
                this.loading = true
                await cb()
            } catch (e) {
                 console.error('Error capture', e)
            } finally{
                this.loading = false}}}const fetch1 = loadingAndCatch(async() = > {const result = await postFunction(data)
        ...
    })
    const fetch2 = loadingAndCatch(async() = > {const result = await getFunction(params)
        ...
    })
    Copy the code

Have you noticed that higher-order writing can unify the common logic and no longer require common things like loading inside each function?

Next, get to the computed parameter transmission you’re looking for! If you have one of the following questions ๐Ÿ‘‡, make sure this article is clear to you

computed: {
    // Do not know where to write parameters? Is it wholeName plus parameters? Or return funtion with arguments?
    wholeName (???) {
        return function (?????) {
            return. }}}Copy the code

Come on, let’s take the case from the beginning of the article and change it so that you will understand. Here we just keep wholeName2, computed.

  1. inVue sourcePrint in the computedGetter of:'First, execute computed getter'
  2. And in theThe cb wholeName2In print:'Second, perform computed CB'
  3. inThe return of the functionIn print:'Finally, the template (' Boran ') calls and passes in the argument to perform return function'..
/ / the Vue source code<script>
function createComputedGetter (key) {
  return function computedGetter () {
    console.log('Execute first: computed getter')
    var watcher = this._computedWatchers && this._computedWatchers[key];
    if (watcher) {
      if (watcher.dirty) {
        watcher.evaluate();
      }
      if (Dep.target) {
        watcher.depend();
      }
      return watcher.value
    }
  }
}
</script>// App component code<template>
  <div id="app">
    <p>Computed Data transmission: {{wholeName2(' Boran ')}}</p>
  </div>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
      firstName: 'well'}},computed: {
    wholeName2 () {
      console.log('Secondly perform computed CB: wholeName2 CB')
      return secondName= > {
        console.log('Finally execute the function returned by calling computed in our template! ')
        return this.firstName + secondName
      }
    }
  }
}
</script>
Copy the code

Straight to the results! ๐Ÿ‘‡

So we know that we’re passing the parameter to the function that we’re returning and the function that we’re returning is the function that was called by our template

I’m afraid you can’t say it clearly! I will send you a flow chart again. If it is not clear, please call me ~


3. How can I play with computed SET

Is Vue’s one-way data flow difficult to handle at some point?

For example: EMMM, let me give you a set scenario that I usually use

When encapsulating a component, using the V-Model internally causes externally passed values to be modified internally because the encapsulated component receives externally passed data. In order to maintain one-way data flow, we do not recommend changing the value of external data directly inside the component. This is where our computed SET comes into play ~ see an example ๐Ÿ‘‡

<template>
  <! Vmodel = proxyValue; vmodel = proxyValue;
  <el-select
    v-model="proxyValue" 
  >
    <template v-for="(item, i) in options">
      <el-option
        :key="item.value :label="item.label"
        :value="item.value"
      />
    </template>
  </el-select>
</template>

<script>
  export default {
    name: "BaseSelect".props: {
      options: {
        type: Array.default () {
          return[]}},value: {
        type: [String.Array.Number.Boolean].default () {
          return[]}}},computed: {
      proxyValue: {
        get () {
          // The value passed in is returned directly
          return this.value
        },
        set (val) {
          // Changed proxyValue to emit $emit when set is emitted
          this.$emit('update:value', val) 
        }
      }
    }
  }
</script>
Copy the code

At the end, I want to return to the question of whether computed computed is acceptable. Actually, it is true that computed data does not pass parameters, because we cannot directly pass parameters to our callback when we normally use computed data. But that may be wrong, because this article also introduces higher-order functions that, through hacking, allow computed to accept parameters indirectly, so it can accept parameters, right? Personal feeling, if the interview answer to this extent, and then knot from the source level analysis, that this topic is certainly extra points ~!

This article is a little bit of my personal accumulation of computed data in my daily development, and I hope it will help you

If see feel harvest somewhat of, might as well nod praise ~ love you ๐Ÿ‘