Connecting Vue component data to external state sources

I am facing a challenge with integrating a Vue component into a large legacy system that is not based on Vue. This component retrieves data through AJAX requests and displays information based on an array of database record IDs, typically passed at page load time by the server directly embedded in the template as props like this:

let config = {
  records: {{ template_code_outputting_array }},
  ...otherConfigOptions
}

let app = new Vue({
  el: '#app',
  store,
  render: h => h(ComponentName, {
    props: config
  })
})

However, I encountered an issue when trying to embed the component in a screen where users can dynamically select database records using a search-and-add AJAX interface. The challenge is keeping the component in sync with the user's selections so it can be updated accordingly.

Currently, my solution involves calling a method directly on the component every time there's a change in user selection, passing the new selection to update the internal copy:

app.$children[0].recordsChanged(newSelection)

While this works, I feel it is not ideal as it lacks reactivity and seems like a hacky approach. I believe directly addressing a component in this manner is not recommended, especially considering that the function being called is for external use only and not used internally within the component.

I have attempted binding values in data to global variables, although imperfect, given the circumstances, but adding a watch method has not triggered the necessary re-render upon changes. Scalar values do not react due to their pass-by-value nature, and even wrapping them in an object did not lead to the expected reactivity.

Is there a best practice or better way to achieve this functionality, or perhaps my current approach is the most feasible solution?

Answer №1

If you're looking for a solid solution, consider implementing an event bus (as recommended by AfikDeri in the comments). This approach offers a simple and intuitive interface.

Another option is to make your data reactive, although there are certain limitations to be aware of. When initializing a data item with an Object, it will automatically become reactive. As long as any changes to your array follow the approved guidelines, those modifications should reflect properly in your Vue application.

let stuff = [2, 3, 5];

const v = new Vue({
  el: '#app',
  data: {
    reactiveStuff: stuff
  },
  components: {
    myComponent: {
      props: ['arr'],
      template: '<div><div v-for="item in arr">{{item}}</div></div>'
    }
  }
});

setTimeout(() => {
  stuff.push(7);
}, 1200);
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<my-component id="app" :arr="reactiveStuff">
</my-component>

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

Failed to insert a new element into the MongoDB array

After trying the code below to update a document within a collection, I encountered an issue where a new item was not being added to an array in the script. Despite no exceptions being thrown, the array remained unchanged. I am seeking advice from experts ...

Reload the page when the value reaches 1

Hello, I am currently working on creating a system where my index page refreshes when a value in my database is set to 1. However, I am having trouble with the code as only my index.php is not refreshing. index.php <script> interval_timer = setInt ...

What steps can be taken to avoid being logged out automatically upon clicking the back button?

Currently, my code automatically logs out of the application when the browser is closed. However, I am facing an issue where it also logs out when I press the browser's back button and navigate to another page. I would like the code to only logout au ...

Styling a textbox within a gridview using JavaScript

Looking for a way to format a textbox within a gridview using JavaScript? Take a look at how the gridview columns are set up: <Columns> <asp:TemplateField> <ItemTemplate><asp:ImageButton runat="server" id="imgbtnEnterAmt" ...

Ajax is not displaying the pound sign (£)

I'm having trouble displaying the British pound symbol on my website. I've tried using HTML codes for the pound sign, but it's still not showing up. Here's what I've tried: var price = '£' + parseInt($('#pricetag& ...

Combining two or more arrays containing similar values into a single array

Within my array, there are 100 subarrays, each containing 3160 values of an object with two attributes: a sequence number (which only appears if it is present as 1), and another value of either 0 or 1. My goal is to merge all 100 arrays into one single ar ...

MXGraph has an issue where edges fail to be redrawn after being moved

Perhaps this question may seem trivial, but I am facing an issue in my code and seeking guidance from the community. I am working on a javascript mxGraph application within Angular7. Specifically, I have modified the ports.html example for my project. Wh ...

Is there a way to assign a dynamic value to an input just once, and then retain the updated value without it changing again

During a for loop, I have an input element (type number) that needs its value modified by decrease and increase buttons: <div class="s-featured-list__item s-featured-list__item--expandable" v-for="(item, itemIndex) in category.items" ...

Show a continuous flow of images on the screen without needing a webpage refresh, providing the user with a seamless video

I'm working with a servlet that generates a series of images, and I'm looking for a way to display them on a JSP page without refreshing the entire page. I was considering using applet or AJAX, but I'm still searching for a more convenient s ...

Direct users to a different page upon reloading the page in Django

Currently working on a web application with the Django framework. In one of the forms in my app, I am looking to automatically redirect to a new page upon reloading the current page, rather than when the form is submitted. Any insights from the community w ...

Images are not loading in NextJs image component on a Digital Ocean deployed application

I recently encountered an issue with my NextJs project. While using the NextJs Image Component for images, everything worked perfectly fine when running locally. However, after deploying the project on Digital Ocean, all the images served through the Next- ...

Retrieve and save only the outcome of a promise returned by an asynchronous function

I am currently working on an encryption function and have encountered an issue where the result is returned as an object called Promise with attributes like PromiseState and PromiseResult. I would like to simply extract the value from PromiseResult and s ...

Locate the index of an item within an array of objects based on a matching property in the

My current situation involves having an array of objects structured like this : [ {label: "<p>Opacity | %<br/></p>", customRow: false, id: 0, items: Array(13)}, {label: "Brand_hs_id", customRow: false, id: 0, items: A ...

Animation of disappearing blocks covering the entire screen

I am currently working on creating a slider with fading blocks animation similar to the one shown here. The challenge I am facing is making it fullscreen, where the height and width will be variable. This makes using the background-position trick ineffecti ...

Steps to alter the color of a JSONLoader-generated object with a simple click

Recently, I've been delving into Three.js and managed to create an object using the JSONLoader. The material of the object is currently grey in color. My goal now is to allow users to change the color of the object by clicking on a button that I have ...

Using AJAX to load a PHP file in CodeIgniter is a great way to

I'm a beginner in the world of web development and I need help with loading my PHP file containing HTML content to update the span element. My framework of choice is CodeIgniter. Every time I try, I encounter an error. Below is my JavaScript code: ...

Please refrain from submitting the form until the slow AJAX jQuery process has finished

My form is experiencing a delay of almost 4 seconds due to the Ajax jQuery I am using, which creates fields within the form. This delay causes some users to submit the form before the necessary fields are created. I need a way to prevent the form from bein ...

The main content will be displayed on the sub-routes of the child

I'm feeling uncertain about the routes for children. For example, I have an 'About' route with 'me' as a sub-route: { path: '/about', name: 'About', component: About, children: [ { ...

Persistent Angular Factory Variables Showing Outdated Data - Instances Stuck with Old Values

One of the challenges I faced was setting up a resource factory to build objects for accessing our API. The base part of the URL needed to be determined using an environment variable, which would include 'account/id' path segments when the admin ...

Unplanned pathways on a node-based server

Building a server, I've utilized the following code snippet: function uniqueString(length) { var result = ''; var characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; for (var i = length; i &g ...