What is the reason for setting the initial value of a Vue computed property to a Javascript object property?

Can someone please explain why the Javascript object property, data.test, always holds the initial value of the computed property, square? Even after submitting a number in the input field, data.test remains set to 4. On the other hand, the computed property seems to be working correctly as indicated by the HTML elements, anyNum and square.

Check out the code on this fiddle

<script setup>
import { ref, computed } from 'vue'

const anyNum = ref(2)

const square = computed(() => {
  return anyNum.value * anyNum.value
})

const data = {    
  test: square.value <===== JavaScript object property always equals 4
}

function submitForm() {
  console.log(data)
}    
</script>

<template>
  <p>anyNum: {{ anyNum }} </p>
  <p>square: {{square}} </p>
  <form>    
      <input v-model="anyNum" type="number" >
      <button @click.prevent="submitForm()">
        Submit
      </button>
  </form>
</template>

However, when I change the Javascript object data to a function, then data.test correctly captures the computed value of squared. Visit this fiddle for reference.

<script setup>
import { ref, computed } from 'vue'

const anyNum = ref(2)

const square = computed(() => {
  return anyNum.value * anyNum.value
})

const data = () => { 
  return {
    test: square.value  <===== captures the correct value
  }
}

function submitForm() {
  console.log(data())
}
</script>

Answer №1

data.test does not dynamically update based on user interface changes. It is initialized when the component is created and remains static thereafter, failing to track real-time data. If you want data.test to be recalculated whenever square.value changes, then data must also be a computed property:

const data = computed(() => { 
  return { test: square.value }
})

The reason why your second example functions correctly is because as a function, it will always re-execute/recalculate each time it is called.

Answer №2

If you're looking for more information on reactivity in Vue, I recommend checking out the Reactivity in Depth page of the Vue documentation. In this guide, it explains that when you assign or destructure a property of a reactive object to a local variable, the reactivity becomes "disconnected." This means that accessing the local variable no longer triggers the get/set proxy traps.

As a result, because the `data` variable is a local variable and hasn't been wrapped in `ref` or `reactive`, it behaves like regular JavaScript. So, are you expecting reactivity from plain old JavaScript?

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

Struggling to run npm build in Next.js project due to webpack errors?

After months of developing this application, I encountered a frustrating error when attempting to run npm run build for the first time today. Despite removing next-transpile-modules from my next.config.js and taking various troubleshooting steps like delet ...

Trying to call an applet method using JavaScript will not be successful

When trying to invoke methods of a Java applet using JavaScript, I encounter an issue that requires the site to be added to trusted sites and security set to low in order for it to work properly. Otherwise, an error is thrown: Microsoft JScript runtime ...

What is the best way to create a dynamic URL linking to an external site in Angular 5?

When attempting to create a link like this: <a [href]="getUrl()">click me</a> getUrl() { return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com'); } The link is not clickable. When hovering over the ...

Incorporate a personalized style into the wysihtml5 text editor

Is there a way for me to insert a button that applies a custom class of my choice? I haven't been able to find this feature in the documentation, even though it's a commonly requested one. Here's an example of what I'm looking for: If ...

The Express middleware is not being utilized

There seems to be an issue with the middleware in the code below that is supposed to create a property req.user if req.session.user exists. Unfortunately, it appears that the middleware is not being triggered, causing 'hihihhiihi' to not be print ...

Learn how to utilize JavaScript produced by the `webpack output library` in a `nodejs` application

I'm currently utilizing webpack to bundle my JavaScript into a library that serves two purposes: one for browser usage and the other for integration into Node.js applications. Below is a snippet of my webpack configuration: output: { filename: ...

Ways to move all the elements within a given array

The code checks each variant within the variant array and displays all objects that match the condition or 'undefined' if not. However, in this code snippet, a new array is being created for each item like so: [{id: 'something'}] [{id: ...

What is the best way to provide a static file to an individual user while also sharing its file path

I have integrated jsmodeler (https://github.com/kovacsv/JSModeler) into my website to display 3D models. Currently, users can only select a file using a filepicker or by entering the path in the URL (e.g., http://localhost:3000/ModelView#https://cdn.rawgit ...

What is the best way to save data in MONGO DB with Java programming language?

Creating a blog post feature in my web application has been an interesting journey. Initially, I relied on mysql as the database to store the posts entered in the text area of the blog as an object in JavaScript. The process involved sending this object to ...

Having difficulty sending data through Vue

I need help figuring out how to add an array in Vue.js. The array structure looks like this: "role 1" => [ "role" => "role 1", "hours" => "4" ]; However, when I try to implement it, I enco ...

"Having trouble subscribing? The first attempt doesn't seem to be working

I'm currently working on some TypeScript code that searches for the nearest point around a user in need of car assistance by checking a database. Once the nearest point is identified, the code retrieves the phone number associated with it and initiate ...

What is the best way to generate a new div element when the content exceeds the preset height of the current div?

CSS .page{ width: 275px; hight: 380px; overflow: auto; } HTML <div class="page">dynamic text</div> Is there a way to automatically create new div elements when dynamic text overflows past the fixed height of the init ...

Form submission button gets stuck after AJAX request is made

Hey there, I'm currently working on a form that utilizes Ajax for making a post in Rails 4. The JavaScript in the form includes some validation checks and is supposed to display an alert message upon successful posting. However, I'm facing an iss ...

Encountered an error with the post request in expess.js: TypeError - Unable to access the property 'fullName' as it is undefined

Hey everyone, I'm new to Express and having trouble posting data from Postman. The error message I'm getting is "TypeError: Cannot read property 'fullName' of undefined". Does anyone have any suggestions on how to fix this? Thank you! ...

Utilize separate environment variables for distinct environments within a React project

Is there a secure method to externalize all environment variables, including secret keys, for a React application within a DevOps setup? Our goal is to streamline the build process across different environments, each with its own unique set of environment ...

Utilizing Next.js to dynamically load a component library based on the response from getServerSideProps

I am working on a project that involves multi-tenancy and am looking for a way to dynamically switch between component libraries based on an external response while maintaining server-side rendering. Both component libraries have the same structure, includ ...

transferring data from an express server to a JavaScript script in a jade template

I'm attempting to transfer a value to a variable in JavaScript from Express to a Jade template. Below is my route in Express: app.get('/tmp', function(req, res){ res.render('tmp', { title: 'Temperature&apos ...

Leverage the power of EJS and Node JS by incorporating node modules into

I am having trouble importing my datetimepicker JavaScript and style sheet into my EJS file. Unfortunately, the CSS and JS files are not rendering properly when I run the code. Below is how my code is structured: In the EJS file: <html> <meta n ...

The Jquery .each() method is causing the return value to be undefined

Why is the getColorOptionSelect() function returning an undefined value, even though it has a value when checked with the debugger? I am certain that this issue is related to scope - my apologies for my lack of knowledge in JavaScript. jQuery(document).r ...