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

Tips on customizing the appearance of two Material-UI Sliders across separate components

Looking to customize two sliders, each within their own react component. Slider in the first component const customizedThemeSlider1 = createTheme({ overrides:{ MuiSlider: { thumb:{ color: "#4442a9", marg ...

Invoke the onload event from document.ready using jQuery

Is it possible to trigger the onload event from within jQuery's document.ready function, such as in the example below: $(function() { onloadfunc(param); }); Comparison: <body onload = "onloadfunc(param);"> Do the above two methods achieve th ...

Is there a way to retrieve the response body in Express framework?

In my NodeJS API using Express, I am attempting to save the response body of a request. To achieve this, I have created two middleware functions. app.use((req, res,next) => { res.status(404).json({ errors: [{ field: "url", ...

A step-by-step guide for updating a minor version of Angular with Angular CLI

I've been searching online for the answer to this straightforward question, but can't seem to find it anywhere... In my angular 4 project (made with angular cli), I want to utilize the newly introduced http interceptors in version 4.3. Could so ...

req.next does not exist as a function [END]

I am currently working on developing a website and I have encountered an issue in the dashboard stage. The error message TypeError: req.next is not a function keeps appearing, particularly when trying to create a subpage for the dashboard. I am utilizing t ...

What could be causing the PAGE CSS to malfunction?

I am looking to export HTML text as a word document with A4 size and portrait orientation. My JavaScript currently allows me to export the text, but it appears like a webpage format rather than in A4 or portrait mode. I have tried adding @page CSS styling ...

Which is the most efficient method for incorporating Vue.js into Laravel projects: Inertia.js or Laravel UI?

I'm currently knee-deep in a Laravel project and now I'm onto the Vue.js integration part. After doing some research, I've discovered that there are multiple ways to bring Vue into a Laravel project, with Inertia.js and Laravel UI being the ...

How to apply multiple filters in JavaScript?

I have a set of objects that require filtering. If the object has an active status of true, it should always be included in the filtered result regardless of other conditions. If there is text entered for search, then the remaining items should be filter ...

Sorting a list based on user-defined criteria in Ionic 3

Currently working on a project using Ionic and Firebase, I am faced with the task of comparing arrays produced by users with those stored in Firebase. This comparison is essential for filtering a list of products. The user can reorder a list containing 3 ...

An issue arose when trying to display React components within an Angular application

Attempting to incorporate React components into an Angular 7 application has been a challenge for me. While I have successfully rendered simple React components, I encountered the following error message (displayed in the browser console) when attempting t ...

Implement using a variable as a key for an object in a reducer function

I am facing an issue with constructing an object. The string, named "SKU" in this scenario is being passed through action as action.name. Although I have all the necessary data in the reducer function, I need to dynamically replace the hardcoded SKU with ...

Displaying a 404 error page in Vue Router 4 when users refresh the page

I'm currently developing a headless WordPress theme using Vue 3. After implementing vue router, everything seems to work fine when the page is initially loaded. However, I've encountered an issue where if the user changes the route and then refr ...

React Alert Remove Alert: Each item in a list must be assigned a distinct "identifier" prop

How can I resolve the React warning about needing a unique "key" prop for each child in a list? I'm trying to eliminate the warning that says: "Each child in a list should have a unique key prop." The code snippet causing this warning is shown below ...

Guide to sending a post request in Node.js using Mongoose

I recently tried to follow a tutorial (https://medium.com/weekly-webtips/building-restful-apis-with-node-js-and-express-a9f648219f5b) from 2 years ago to build an API. However, I'm struggling to update the code to work with more recent changes in the ...

Having trouble with integrating user input from HTML into a JavaScript file to execute a GET request

I am currently working on a project to create a website that integrates the google books API for users to search for books. To start, I have set up a server using express in index.js at the root of the project directory, and all my static files are stored ...

Is it possible to implement formvalidation.io in a React project that is using Materialize-css?

Can the formvalidation.io plugin be used with React and Materialize-css in a project? My project consists of multiple input components that may or may not be within a form. I want to utilize formvalidation for input validation. However, I am unable to find ...

A visually stunning image showcase with dynamic resizing and strategically placed white spaces using the m

I'm attempting to create a responsive image gallery using the Masonry jQuery plugin, but despite reading numerous articles and forum posts on the topic, I can't seem to get it to work properly. The gallery is displaying many blank spaces. My app ...

I am encountering a TypeError that says "Cannot read properties of undefined (reading '$router')". Can anyone explain what this error means and provide guidance on how to resolve it?

$Happy New Year! I'm currently facing an issue with setting up a redirect after retrieving an authentication token. The console keeps throwing a "TypeError: Cannot read properties of undefined (reading '$router')" error, and the user is not ...

The issue with the $(window).width() property not functioning correctly in Internet Explorer

Currently, I have a Div element with absolute positioning: <div id="target" style="height: 300px; position: absolute; top: 275px;"></div> My goal is to calculate the horizontal resolution of the screen using JavaScript. With this width, I the ...

Replacing data in a Node server

I am currently working on a server that temporarily stores files in its memory before uploading them to the database. Below is the code snippet I'm using: uploadImage(file, uid, res) { var fs = require('fs'); mongoose.connect(config ...