Employing a dynamic array within a module

Having some trouble using a reactive array in my component. It seems to work fine with an object, but when it comes to an array of objects, the view doesn't update as expected.

Any suggestions on how to ensure the view gets updated when the array is modified?

var self = currentClassInstance // this
 
self.store = {
    resources: Vue.reactive([]),
    test:  Vue.reactive({ test: 'my super test' }),

    setResources(resources) {
        // The view isn't updating with this method. Any ideas why?
        this.resources = resources

    }, 
    setResources(resources) {
        // This one successfully updates the view
        this.test.test = "test ok"
    },  
}


....

const app_draw = {
    data() {
        return {
            resources: self.store.resources,
            test: self.store.test,
        }
    },
       
    updated() {
        // It seems like the 'updated' event is triggered for "test" but not for "resources"
        console.log('updated')
    },
       
    template: '<div v-for="(resource, key) in resources" :data-key="key">{{resource.name}}</div>'
};
....

Answer №1

As specified in the official documentation :

Reactive:
When given an object, it generates a reactive proxy of the original item. Similar to Vue 2.x's Vue.observable()
....
The reactive conversion is "deep": impacting all nested properties. In the ES2015 Proxy-based execution, the resulting proxy varies from the original object. It's better to work exclusively with the reactive proxy and not depend on the initial object.

I propose assigning the array to a field named 'value' within the reactive parameter, similar to what you did with test :

resources: Vue.reactive({value: []}),

Then use resources.value = someVal to modify that value.

Answer №2

An efficient method

let data = reactive([]);

// initialize data array
data.length = 0;
data.push(...elements);

Answer №3

In addition to what has been mentioned, there are two primary methods for managing reactive arrays.

Option 1: Utilizing a single array with mutable values

const list = reactive([])
list.length = 0 // clear
list.push(...items)

Option 2: Converting the array reference to immutable values

const items = ref([]) // similar to reactive({value:[]})
items.value = ["Marvelous", "day", "isn't it?"]

Both approaches will prompt reactive updates.

Answer №4

There are a couple of important things to note here:

  • resources: Vue.reactive({value:[]})
    might not be necessary if you make the entire store reactive from the start.
  • Instead of using data() for a local copy, consider accessing the single source of truth (the store) using a computed property like Vuex does.
var self = currentClassInstance // reference to this

self.store = Vue.reactive({
  resources: [],
  setResources(resources) {
    this.resources = resources
  }, 
})

const app_draw = {

  computed: {
    resources() {
      return self.store.resources
    }
  }
       
  template: '<div v-for="(resource, key) in resources" :data-key="key">{{resource.name}}</div>'
};

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

The use of jQuery.parseJSON is ineffective for a specific string

Why isn't jQuery.parseJSON working on this specific string? ({"stat":"OK","code":400,"data":[{"title":"Development Convention","event_type":false,"dates_and_times":[{"date":"28\/03\/2012","start_time":"10:00 AM","end_time":"10:00 AM"},{"dat ...

What is the best way to retrieve the specific property from a bound function?

I'm looking to retrieve the value of a specific property from a function that has already been bound. function foo(){ console.log(this.a) } const bar = foo.bind({a:1}) bar() // Outputs 1 bar.getThis() // expected result is { a: 1 } Given the code ...

Mistaken data retrieved from a knockout observable array

My current project involves developing a web application using Asp.Net Mvc, where I am utilizing knockout Js to retrieve and send data to the Html View after manipulating the data. For instance, let's consider the data in an array called datainput: ...

What is the best method for storing dynamic values and attribute labels in a state within a React.js application?

I am currently working with react js. On my single product page, I have an array of objects called attributes that I need to display in the user interface. Here is a preview of how it looks: https://i.sstatic.net/GttrD.png My goal is to retrieve and stor ...

if statement not recognizing data returned from PHP function

I'm currently working with a function that is being used for an AJAX query: var formData = $(this).serialize(); //store form names and values in an array called 'formData' $.get('filtertest.php',formData,processData); //jQ ...

Tips for assigning a type to a variable that is being configured in Typescript

Within my code, I am utilizing the function PanelService.getSetupOrder(route.params.id) which provides me with 4 specific variables: data pending error refresh While researching the documentation, it was mentioned that by specifying data: order, I could ...

Identify and sort JSON objects based on keys with multiple values

My JSON file contains objects structured like this: [ { "name" : "something", "brand": "x", "category" : "cars" }, { "name" : "something2 ...

What is the best method for transferring data from a submit form in ReactJS to AdonisJS?

Seeking guidance on integrating a ReactJS form with an Adonis API to pass data upon form submission. Snippet from ReactJs file: async handleSubmit(e) { e.preventDefault(); console.log(JSON.stringify(this.state)); await axios({ ...

Tips for executing jsfiddle code within Joomla 3.2

I'm having trouble executing this code on my Joomla website. I have Joomla 3.2 installed with the JCK Editor, but the HTML tags are not functioning correctly. Can someone please assist me in running the following code: $("#text10").keyup(functio ...

The challenge with our unique PHP/JS Analytics Solution

Here's an illustration of the code snippet for Google Analytics: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'userIDhere']); _gaq.push(['_trackPageview']); _gaq.push([&apos ...

Issue with the _.filter function in lodash library when used in a Node.js environment

My goal is to remove rows from a CSV file that already contain email addresses found in Mailchimp. Although I attempted to achieve this with a function, it seems that the number of elements returned is not accurate: async function testDeleteEmails(listID, ...

The PrimeReact components are not displaying the PrimeReact theme properly

I'm currently working on integrating a Menubar component from PrimeReact into my React application. I tried to apply one of the predefined PrimeReact themes by importing it, but the page ended up looking strange. When I imported "./../../node_modules ...

The seamless integration of React.js with HTML

My friend and I are beginners in the world of programming, with a solid grasp of html, CSS, and JavaScript. We're currently collaborating on a small project where we aim to create a chat system. While researching resources for our project, we came acr ...

Troubleshooting the issue of a callback function not properly updating state within the componentDidMount

I am currently utilizing Next.js and have the following functions implemented: componentDidMount = () => { //Retrieves cart from storage let self = this this.updateCart(Store.getCart(), self) ... } updateCart = (cart, self) => { ...

Having trouble with JSON search not functioning as expected in Select2 4.0?

After numerous hours of effort, I finally managed to successfully load and display the json file, complete with the flag icons using Select2 4.0. The code ended up appearing deceptively simple. However, I am now facing an issue where the search function i ...

How to deal with jQuery's set val() behavior on SELECT when there is no matching value

Let's say I have a select box like this: <select id="s" name="s"> <option value="0">-</option> <option value="1">A</option> <option value="2" selected>B</option> <option value="3">C</option> </ ...

Using a structural directive in Angular 2 that accepts a String as an input

I am attempting to develop a custom structural directive using the example provided here When trying to pass a string as an input with a slight modification, I encountered an issue where the input value was returning 'undefined' when calling th ...

Vuejs and its unique feature of nested and interconnected slots

Utilizing Vuejs, I have developed two components known as First and Second. The component First renders the component Second. Second contains a named slot. First includes a <template> to fit into the named slot of Second. Within the <template> ...

What is the best way to showcase nested array information from a JSON file on an HTML webpage?

students.json { "students": [ { "studentname": "Rohit Kumar", "grade": "A", "student": [ { "SNo": "1", "Subject": "Maths", "Concept": "Numbers" }, { "SNo": "2", ...

Sequence of successive jQuery requests

Currently, I have a series of ajax calls that must be executed sequentially, without the possibility of being performed in parallel. The function performSeriesofCalls essentially makes ajax calls in the specific order of Call1 -> Call2 -> Call3 -> ...