donkey
donkey

Reputation: 303

Why vue computed function could destructuring assignment the parameter when didn't have argument?

new Vue({
      el: "#app",
       data: {
         value: "text",
       },
       computed:{
        all: function({value}){
          return value
        }
       }
      });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  {{ value }}
  <br>
  {{ all }}
</div>

Didn't see this usage on Vue document.

but I saw this on my project, why this usage could work?

   computed:{
    all: function({value}){
      return value
    }
   }

First i think when function didn't get argument, would take "this" be the argument. see below.

but is wrong. so why computed didn't get argument, Destructuring assignment the parameter still work?

var value = "couldn't fly";
function ref ({value}){
  console.log(value)
}

ref({
  value : "could fly"
})

// didn't get window
try{
  ref();
}catch(e){
  console.log('error')
}


// ===================================================


class cal {
  constructor(){
    value : "couldn't walk"
  }
  ref({value}){
    console.log(value, "in Class")
  }
}

let calRef = new cal;
calRef.ref({
  value: "could walk"
})


// didn't get the constructor value
try{
  calRef.ref()
}catch(e){
  console.log('error')
}

Upvotes: 2

Views: 899

Answers (1)

Phil
Phil

Reputation: 164913

This is documented in the API guide...

Note that if you use an arrow function with a computed property, this won’t be the component’s instance, but you can still access the instance as the function’s first argument

new Vue({
  el: "#app",
  data: {
    value: "text",
  },
  computed: {
    all (vm) {
      console.log('from all, is vm equal to this?', vm === this)
      return vm.value
    },
    arrowed: vm => vm.value.toUpperCase(),
    destructuredArrow: ({ value }) => value.toUpperCase()
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>

<div id="app">
  <pre>value = {{ value }}</pre>
  <pre>all = {{ all }}</pre>
  <pre>arrowed = {{ arrowed }}</pre>
  <pre>destructuredArrow = {{ destructuredArrow }}</pre>
</div>


Just found a handy extra hint... this same pattern applies to a component's data function

export default {
  props: { someProp: String },
  data: vm => ({ localCopy: vm.someProp })
}

Upvotes: 3

Related Questions