Vue.js version 3 presents an issue where the reactivity of a `v-model` is lost when the `data()` function is transformed into `

Exploring this simple example, we have an input and a p element that displays the input value:

const App = {
  data() {
    return {
      message: "hello world!"
    };
  }
};


Vue.createApp(App).mount('#root');
<script src="https://unpkg.com/vue@next"></script>
<div id="root">
  <input v-model="message"/>
  {{ message }}
</div>

Initially, changing the input text updates the content of the p element. However, if we replace data() with setup(), the changes to input no longer reflect in the p:

const App = {
  setup() {
    return {
      message: "hello world!"
    };
  }
};


Vue.createApp(App).mount('#root');
<script src="https://unpkg.com/vue@next"></script>
<div id="root">
  <input v-model="message"/>
  {{ message }}
</div>

To address this issue, we can use ref for the message:

const App = {
  setup() {
    const message = Vue.ref("hello world!");
    return {
      message
    };
  }
};


Vue.createApp(App).mount('#root');
<script src="https://unpkg.com/vue@next"></script>
<div id="root">
  <input v-model="message"/>
  {{ message }}
</div>

But why is this necessary? Why doesn't it work as expected by default?

One possible explanation is that the object returned from data() is internally made reactive, while the object returned from setup() may not be observed because it could include methods that do not require monitoring. However, when examining

inputEl.__vueParentComponent.setupState
, it appears to be a Proxy. So, why doesn't it behave as anticipated?

Answer №1

return {...} simply exposes the values to the outside of the setup function. It is recommended to always use ref or reactive to ensure your data is reactive :

setup() {
    const message = Vue.ref("hello world!");
    return {
      message
    };
  }

You can refer to the comment here, which mentions // expose to template :

<template>
  <div>{{ count }} {{ object.foo }}</div>
</template>

<script>
  import { ref, reactive } from 'vue'

  export default {
    setup() {
      const count = ref(0)
      const object = reactive({ foo: 'bar' })

      // expose to template
      return {
        count,
        object
      }
    }
  }
</script>

Additionally, as mentioned in the setup usage with template documentation :

If setup returns an object, the properties on the object can be accessed in the component's template, as well as the properties of the props passed into setup

In Summary

The object returned in the setup function differs from that returned by the data property in the option api

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

Validating dates using JQuery within a specific range of dates

Users can input a date within a specified range in an input field. To enable this feature, I created a new method using the jQuery validator object: $.validator.addMethod("dateRange", function(value, element, from, to){ try { var date = new D ...

Using Unicode JSON in Laravel blade to pass data to React components, encountering an issue with JSON parsing

I currently have a JSON object stored in the database: { "ui": {}, "title": "Hola mundo 2", "values": {}, "properties": {}, "description": "descripcion" } Within the Laravel controller, ...

Creating a form with multiple checkboxes using Material-UI components where only a single checkbox can be selected

Creating a simple form using Material-UI with checkboxes to select one option and push data to the backend on submit is the goal. The Form component structure includes: multiple options represented by checkboxes only one checkbox can be selected at a time ...

Please refrain from utilizing MUI - useGridRootProps outside of the DataGrid/DataGridPro component

When we click on "Filter" in the context menu of our DataGrid, we encounter this error. We are working on implementing a component hierarchy for the DataGrid as follows: MigrationJobTable.tsx: return ( <div data-testid='migrationJobTa ...

Are you looking for a way to prevent the default behavior of an event in angular-ui-router 1.0.x? Check out

Recently, I made a change in my code where I replaced $stateChangeStart with $transitions.onStart $rootScope.$on('$stateChangeStart', function(e, ...){ e.preventDefault(); // other code goes here... }); Now, the updated code looks lik ...

Error: The function 'myAppController' is not defined and is therefore not a valid argument

I am trying to incorporate my service into my controller and print a message to the console (in the Auth Service), but I keep encountering this error: Argument 'myAppController' is not a function, got undefined. Can you help me figure out what I& ...

Gain access to Google Analytics without the need for page consent by utilizing JavaScript

I am currently building a dashboard with Atlasboard. My goal is to retrieve Google analytics data such as page views, and I plan to run specific queries which can be found here. Is there a method to access my Google analytics data without the consent pag ...

Any ideas on how to extract binary data from PHP passthru using a JavaScript ajax request?

I am facing an issue with retrieving and playing an audio file from a server using JavaScript. The ajax call in my code doesn't seem to callback, and I'm not certain if I'm handling the audio correctly in JavaScript. Below is the PHP file t ...

Unable to establish a connection with the docker container

I have developed a server-api application. When running the app on my localhost, only two simple commands are needed to get it up and running: npm install npm start With just these commands, the app runs perfectly on port 3000. Now, I am trying to dock ...

Increase or decrease the quantity of items by cloning with Jquery and dynamically changing the ID

Currently, I am working on a jQuery clone project where I need to dynamically add and delete rows. Despite searching extensively on Stack Overflow and Google, I only have a basic understanding of how jQuery clone works. Any suggestions would be greatly ap ...

Can TypeScript modules be designed to function in this way?

Seeking to create a versatile function / module / class that can be called in various ways: const myvar = MyModule('a parameter').methodA().methodB().methodC(); //and also this option should work const myvar = MyModule('a parameter') ...

Tips for integrating AngularJS into a webpage

I am currently developing a NodeJS application and I am looking to integrate AngularJS for the client side scripting. After downloading AngularJS via NPM, I encountered an issue where my require statement is not functioning as expected. Can anyone provide ...

Navigate array in vue-chart.js

I've been utilizing Vue-chartjs with Laravel 5.7 for my project. The goal: I aim to pass an array to Vue so that I can dynamically generate a chart by looping through specific values. My approach so far: Here's the array I'm working with ...

Guide to placing a button on the same line as text with the use of JavaScript

Does anyone know how to add a button to the right of text that was added using JS DOM? I've tried multiple techniques but can't seem to get it right - the button always ends up on the next line. Any tips on how to achieve this? var text = docu ...

What could be causing the onClick event handler to trigger twice in my create-react-app?

Does anyone know why the "upvote" onClick handler is triggering twice? Even though the logs show it's only running once, the score increases by 2 export default class Container extends Component { constructor(props) { super(props); this.sta ...

How to locate the position of a specific word on a webpage using jQuery

In my div, I am struggling to search like an editor. Despite multiple attempts, I have not found a solution yet. Can someone please advise me on how to resolve this issue? <div id="content"> <p> Lorem Ipsum is simply dumm ...

Issue occurs when using Angular Firebase $createUser method

I'm stuck on this issue. I'm attempting to set up a user with AngularFire using $firebaseAuth instead of the deprecated FirebaseSimpleLogin, as advised in the documentation. I am confident that the form is submitting a valid email and password, b ...

The option to "open in new tab" is absent from the right-click menu when clicking a link on a website

Why does the option to open a link in a new tab not appear when using JavaScript or jQuery, but it works with an anchor tag? I have tried using window.location and window.open, as well as adding the onclick attribute to a div, but the option still doesn&ap ...

Managing extensive text-based passages or titles within React.js

I'm curious about the most effective way to store lengthy text-based HTML elements like <p>, <h1>, <h2>, <h3> in React.js for optimal semantics. After delving into the realm of react.js documentation, I grasped that we have the ...

Issue with Vuex causing error message "TypeError: Unable to access property 'getters' of an undefined object"

I am facing an issue where Vuex seems unable to locate my getter for the loading_state. While the vuex state and getter are visible in the Vue developer tools, I am unable to access them within my application. I have attempted to make changes such as mod ...