Is it possible for the Vue computed function to use destructuring assignment for the parameter even when no arguments are provided?

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>

Unexpectedly found this unconventional usage within my Vue project.

Although not documented, it seems to be functioning as expected.

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

Initially assumed that when no argument was passed to the function, 'this' would automatically be used as an argument. Referencing the example below:

However, contrary to expectations, the destructuring assignment works even when computed values do not receive any explicit arguments.

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

ref({
  value : "could fly"
})

// did not output 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"
})


// did not output the constructor's initial value
try{
  calRef.ref()
}catch(e){
  console.log('error')
}

Answer №1

The information pertaining to this topic can be found in the official API documentation...

It's worth noting that when using an arrow function in a computed property, this will not refer to the component instance. However, you can still access the instance as the first argument of the function.

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>


I recently discovered a useful tip... the same rule also applies to a component's data function

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize a singular ng-model for efficiently filtering and presenting filtered data

Recently, I encountered an issue with a HTML select element that is used to sort a list. The code for the select element looks like this: <select ng-init="sortMethod=sortMethods[0]" ng-model="sortMethod"> <option ng-repeat="sortMethod in sortMe ...

Writing a function to determine if an HTML element is present

Is there a way to create a function that checks for the existence of an element with a specific id? I have a list of IDs stored in an array: let CartArray = ["cart-0", "cart-1", "cart-2", "cart-3"]; This is the Java ...

Activate SVG graphics upon entering the window (scroll)

Can anyone assist me with a challenging issue? I have numerous SVG graphics on certain pages of my website that start playing when the page loads. However, since many of them are located below the fold, I would like them to only begin playing (and play onc ...

Creating custom modals for individual elements using PHP

Currently, I am working on a project that involves allowing users to select an item from a list retrieved from a MySQL database. The goal is to have buttons generated based on the selected item, shown below: Here is a trimmed version of my code thus far: ...

Here is the code I have written to implement a date-picker event that retrieves specific records based on the selected date

I'm struggling with inserting a question here. Can someone provide assistance? $query = ("SELECT orders.customer_id, customer.name, customer.email, customer.address, customer.phone_number, orders.product_id, orders.total_units, orders.total_price, or ...

The alteration of arrays within React.js

I've been working on this function: setNotActiveWalletsList = () => { const { GetAccounts } = this.props; let shallowCopyOfWalletsArray = [...GetAccounts]; const notActive = shallowCopyOfWalletsArray.filter(user => user.active != ...

worldpay implements the useTemplateForm callback function

My experience with implementing worldpay on my one-page Angular app (Angular 1.x) has been mostly positive. I have been using the useTemplateForm() method to generate a credit card form and retrieve a token successfully. However, I have encountered an issu ...

Utilizing the super method within a sails.js controller

Is there a way to call the default parent method of a redefined standard method in a controller created in sails.js? module.exports = { create: function(req, res) { //test some parameters if (condition) { //call regul ...

Issue with HTML5 Canvas y-axis dimensions

I am attempting to create a basic animated HTML canvas with a moving block controlled by WASD keys. I encountered an issue where drawing a 5x5 rectangle appeared to be 5x10 on the canvas. Upon inspecting my code and logging the position of the element, I d ...

Odd behavior observed while running npm scripts in the npm terminal

Included in my package.json file are the following dependencies: "devDependencies": { "chromedriver": "^2.37.0", "geckodriver": "^1.11.0", "nightwatch": "^0.9.20", "selenium-server": "^3.11.0" }, "scripts": { "e2e": "nightwatch -c test ...

What is the best way to transfer a variable from a node server to a javascript client when the page is first

My web application is mainly static, but I need to dynamically send the user's username if they are logged in and the room name they specify in the URL to the client-side JavaScript upon page load. Finding a simple solution has been challenging for me ...

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...

The ultimate guide to personalizing group titles in Angular UI-Select

Is there a way in Angular ui-select to customize the group label? I want to make it larger than the selection items as shown in the image below. https://i.stack.imgur.com/ofcak.png The list is currently grouped by country, but how can I adjust the size o ...

Tips for saving and accessing Shopping Cart items using localstorage

As I develop a shopping cart for an e-commerce site, I aim to utilize browser localstorage to store the products. The functions that have been added to my code include: - addToCart(): triggered when the "Add to Cart" button is clicked. - addProduct(): ...

Can you explain the significance of the v-on="..." syntax in VueJS?

While browsing, I stumbled upon a Vuetify example showcasing the v-dialog component. The example includes a scoped slot called activator, defined like this: <template v-slot:activator="{ on }"> <v-btn color="red lighten-2" ...

After updating Angular Material, the alert dialogs are now transforming into a large dark region

Recently, I encountered an issue while attempting to upgrade my old version of angular-material (v0.9.0) to a newer one. The reason behind this upgrade was the necessity to utilize the new htmlContent for an alert using $mdDialog. However, after replacing ...

Fetch routes from an external API using a component and integrate them seamlessly into the router

I want to fetch my routes from an external API, considering that some users may not have the necessary permissions to access a particular module. My navbar makes an API request to retrieve all available modules. These modules contain the file path for the ...

Translating SQL to Sequelize Syntax

I have an SQL query that I need to rewrite as a sequelize.js query in node.js. SELECT historyTable1.* FROM table1 historyTable1 WHERE NOT EXISTS ( SELECT * FROM table1 historyTable2 WHERE historyTable2.id=historyTable1.id AND historyTable2.da ...

Match one instance of a character in a regular expression pattern while simultaneously matching two occurrences of a different character

I am attempting to create a function that can match one occurrence of a certain character and two occurrences of another character simultaneously. For instance, in the string "_Hell_o", I want to match the first underscore (_) and in the string "++Hello", ...

Is there a way to prevent an external script from making changes to an inline style?

There is a mysterious script running on a page that seems to be controlling the height of an inline style. The source of this script modifying the height property is unknown. <div class="vgca-iframe-wrapper wpfa-initialized" style="heigh ...