Issue with passing reactive property to component in Vue 3 application

I am currently working on a Vue 3 application and I am in the process of setting up a store for state management. Within this application, I have several important files that play different roles:

  • app.vue
  • component.vue
  • main.js
  • store.js

These files contain crucial code snippets, such as:

store.js

import { reactive } from 'vue';

const myStore = reactive({
    selectedItem: null
});

export default myStore;

main.js

import { createApp } from 'vue';

import App from './app.vue';
import myStore from './store';

const myApp = createApp(App);
myApp.config.globalProperties.$store = myStore;
myApp.mount('#app');

component.vue

<template>
  <div>
    <div v-if="item">You have selected an item</div>
    <div v-else>Please select an item</div>
    <button class="btn btn-primary" @click="generateItem">Generate Item</button>
  </div>
</template>

<script>
  export default {
    props: {
      item: Object
    },

    watch: {
      item: function(newValue, oldValue) {
        alert('The item was updated.');
      }
    },

    methods: {
      generateItem() {
        const item = {
          id:0,
          name: 'Some random name'
        };
        this.$emit('itemSelected', item);
      }
    }
  }
</script>

app.vue

<template>
  <component :item="selectedItem" @item-selected="onItemSelected" />
</template>

<script>
  import Component form './component.vue';

  export default {
    components: {
      'component': Component
    },

    data() {
      return {
        ...this.$store
      }
    },

    methods: {
      onItemSelected(item) {
        console.log('onItemSelected: ');
        console.log(item);
        this.$store.selectedItem = item;
      }
    }
  }
</script>

The central concept of this setup is to manage state using a reactive object, which is then passed down to the component as a property. The component can modify the object's value when a user interacts with the "Generate Item" button.

I have noticed that the selectedValue is successfully passed down as a property. I confirmed this by manually assigning a dummy value to selectedValue for testing purposes. Additionally, the onItemSelected event handler functions correctly, indicating that events are being transmitted upwards effectively. However, despite updating the selectedItem within the event handler, the changed value does not propagate back down to the component. What could be causing this issue?

Answer №1

$store.selectedItem becomes non-reactive at this point, as it is only accessed once in the data block:

data() {
  return {
    ...this.$store
  }
}

To maintain reactivity, it needs to either be converted into a ref:

data() {
  return {
    selectedItem: toRef(this.$store, 'selectedItem')
  }
}

Or transformed into a computed property:

computed: {
  selectedItem() {
    return this.$store.selectedItem
  }
}

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

Encountering issues with parsing JSON data following its transmission through an Ajax request

Client Side Once an object has been processed with JSON.stringy, it is sent in this format to a node-server via a POST request: {"id":"topFolder","parentPath":null,"name":"newProject","is":"root","children":[]} The request is sent from the client side u ...

"Concealing Querystrings in Node.js and AJAX: A Step-by-Step

I want to create a simple login form using the ajax Post method. However, I am having issues with the querystring still appearing in the URL. Can anyone help me resolve this issue? Thank you for any assistance! [ https://i.stack.imgur.com/R76O4.png http ...

The limitations of Typescript types influence the program's behavior

As a newcomer to the Typescript environment, I am currently developing a test application to familiarize myself with it. However, I have encountered an issue regarding type restrictions that seems to be not working as expected. In my class, I have defined ...

Troubleshooting issues with Three.js and .obj file shadows

I've been diving into learning Thee.js, and while it's fairly straightforward, I've hit a roadblock with getting shadows to work. Despite setting castShadows, recieveShadows, and shadowMapEnabled to true in the appropriate places, shadows ar ...

What distinguishes node from node js?

Following the instructions on https://nodejs.org/en/download/package-manager/, I installed Node.js. Upon checking the current version using: :~/Downloads$ nodejs -v I discovered that I was running v4.2.6, which is an older version. Deciding to update, I ...

Issues with Three.js raycaster intersectObjects

I am currently working on a 3D scatter plot where spheres are used to represent the points, and I am attempting to show information from the points when they are clicked. After researching various answers on this platform, I believe I am moving in the righ ...

Can you explain the purpose of the .json() function in Angular2?

Can you explain the purpose of the .json() function within http requests in Angular2? Here is an example code snippet: this.http.get('http://localhost:8080/getName') .subscribe(res => this.names = res.json()); Is it correct to assume that t ...

What is the best way to use a button to hide specific divs upon clicking?

Is there a way to use a button onclick event to hide specific divs within a parent div? I've tried using .toggleClass('.AddCSSClassHere') but I'm not sure how to apply it to multiple divs. The jQuery snippet provided only allows me to h ...

The public folder in Node.js is known for its tendency to encounter errors

I'm facing an issue with displaying an icon on my website. Here is the current setup in my code: app.js const http = require('http'); const fs = require('fs'); const express = require('express') const path = require(&apo ...

JQuery Chosen extension - Go back to "Choose an option"

This is a select element with the Chosen plugin applied to it: <label class="radio-inline"><input type="radio" name="reset" value="reset">Reset</label> <select id="listclient"> <option value=""></option> <option val ...

Troubleshooting problem with Materialize CSS in UI router

Incorporating Materialize CSS along with Angular's ui.router for state management and HTML rendering has led to a challenge. Specifically, the Materialize Select component is not initialized upon state changes since Materialize components are typicall ...

Importing a JS file within a JS script

Currently, I am facing a requirement to dynamically include a .js file (more jQuery code) within a working jQuery script. Specifically, when my page gets authenticated, I need to add a specific script file. I am looking to accomplish this in ASP.Net MVC. ...

What is the best way to change a JSON string into an array of mysterious objects?

I am currently working on a flashcard generator project and I am dealing with a JSON String that is quite complex. The JSON String contains multiple arrays and objects structured like this: data = [{"front":"What is your name?","back":"Billy"},{"front":"H ...

Adjust the browser zoom level to default when navigating to a new page

My mobile site uses ajax to load pages, and I'm looking to implement a feature that resets the zoom level when a page changes. Is there an effective way to detect if a user has zoomed the view while browsing a page? Currently, I have been able to ch ...

Detecting unutilized space in a collection of divs with varying sizes using JavaScript and CSS

To better understand my issue, I created a StackBlitz demo: https://stackblitz.com/edit/angular-aqmahw?file=src/app/tiles-example.css Screenshot My tiles can have four different widths (25%, 50%, 75%, 100%). The tiles must fit on only two lines, so if a ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

How to toggle visibility of a Bootstrap modal using VueJS (using CDN) without displaying the overlay

I have integrated VueJS into a single page using the CDN, which prevents me from utilizing bootstrap-vue. The functionality to display and hide a modal based on the value of the showModal data is currently working. However, the gray overlay surrounding th ...

Having trouble with Ajax retrieving the updated JSON file version

I'm pretty new to coding and terminology in general, so I've done my best to simplify my code, although it might still have redundancies. Appreciate your patience in advance. My task involves using an ajax and php script to write data to a file ...

Tips for properly removing Bootstrap 4 tooltips when deleting their corresponding DOM element using html()

In my Bootstrap 4 project, I've implemented a live search box that displays results with tooltips for longer descriptions. I've written jQuery scripts to hide the search results and their parent div when certain events occur, like clearing the se ...

Error: The reset function cannot be executed on $(...)[0]

Purpose My aim is to clear a form once it has been successfully submitted. Problem Upon submitting the form, I encounter the error message in my console: Uncaught TypeError: $(...)[0].reset is not a function When examining the content before resetting, ...