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

What is the best method for saving a chosen radio button into an array?

I am currently developing an online examination system where questions are retrieved from a database using PHP and displayed through AJAX. I am facing an issue where I am unable to capture the selected radio button value and store it in an array. Despite e ...

Switching between rows in a table once information has been added to an array | Vue

I'm currently working on creating a table with rows that toggle when a 'View' button is clicked. The table is generated using a for loop for an array. I've successfully implemented the toggling functionality for preloaded data, but enco ...

Include the component with the function getStaticProps loaded

I am currently working on a project using NextJs and I have created a component to load dynamic data. The component works fine when accessed via localhost:3000/faq, but I encounter an error when trying to import the same component into index.js. It seems l ...

Having trouble with enter key input not triggering?

I have scoured various resources for answers to my query, including Stackoverflow. Unfortunately, none of the posts I came across have helped me resolve my issue with getting the enter key to work in my project for FreeCodeCamp on Codepen. When I press the ...

Real estate listing featuring unique symbols

How do I include the ' character in properties when writing my object, like this: const championsList = { Kha'Zi: '...', }; Any suggestions on how to achieve this? ...

Retrieve the key value pair from the AJAX response

I am trying to retrieve specific values from a cross domain call to a PHP script. The response I receive is as follows: response=2&count=15&id=84546379&firstname=adsa&emailstatus= My goal is to extract the values of 'response' a ...

Switch out the image for a placeholder whenever the src is updated

I need to update an image with a dynamic src value <img :src="image.url"> Currently, when the image.url changes, the old image remains in place until the new one loads. This delay can create a strange effect as the text details change before the im ...

All menus effortlessly sliding out simultaneously

I'm having an issue with my navigation bar. I want each link to slide its corresponding DIV up or down when clicked. However, all the DIVs are sliding and when clicking on the same link everything slides up. How can I fix this problem? This is my HT ...

Dropdown Pattern with React CTA Modal

While using MaterialUI's ButtonGroup for a dropdown menu, I encountered an issue trying to set up a series of CTAs that are easily interchangeable within it. The goal is to have all components reusable and the choices in the dropdown dynamic. const C ...

Removing a row from an HTML table using JavaScript

I have a piece of JavaScript code that is responsible for managing an HTML table. One of the functionalities it needs to support is deleting a row from the table. Currently, I am using the following snippet of code to achieve row deletion: var rowToDele ...

Mapping an array using getServerSideProps in NextJS - the ultimate guide!

I'm facing an issue while trying to utilize data fetched from the Twitch API in order to generate a list of streamers. However, when attempting to map the props obtained from getServerSideProps, I end up with a blank page. Interestingly, upon using co ...

"Is it possible to use a Twitter widget with Mootools

I have been attempting to create a marquee for my twitter Account on my website. After some trial and error, I was able to achieve this using jQuery. Here is the code I used: <div id="twitter"> <p> Loading.....</p> <n ...

invoke the modal function from a separate React file

I am currently studying react and nextjs. I am experimenting with calling a modal from another file but unfortunately it's not functioning as expected. Here is the code I used: Signin.js import { Modal } from "react-bootstrap"; import { u ...

How come certain jQuery scripts and icons are not functioning properly after the partial view is loaded in ASP.NET Core?

I am encountering an issue on my page where I have a list of information that can be searched using fields and Ajax. When I reload the information as a partial view, none of the jQuery code seems to work after the reload. What could be causing this problem ...

Strange anomalies arising in frontend Apollo and GraphQL integration

Currently, I am working with nuxt.js and apollo. One issue I am facing is that when I click a button, it sends a request to the graphql server. The strange part is that the first time I click the button, everything works as expected. However, when I clic ...

tips for generating a random number for direct display

Can anyone help me figure out how to automatically display the total of numbers from this script on my blog post without having to click anything? Additionally, I need it to update if the browser is refreshed. ` http://jsfiddle.net/BenedictLewis/xmPgR/ ...

Discovering a particular element involves iterating through the results returned by the findElements method in JavaScript

I am attempting to locate and interact with a specific item by comparing text from a list of items. The element distinguished by .list_of_items is a ul that consists of a list of li>a elements. I am uncertain about how to transfer the determined elemen ...

Experience some issues with the NextJS beta app router where the GET request fails when using fetch, but surprisingly works

Having an issue with a GET request while using NextJS with the APP dir... The function to getProjects from /project route.ts is not triggering properly. console.log("in GET /projects") is never triggered, resulting in an unexpected end of JSON ...

Having trouble including a YouTube iframe code within the document ready function

I am having trouble getting the youtube iframe API code to work properly within my $(document).ready() function. When I try to add the code inside the function, the player does not load. However, when I move the code outside of the document.ready, the play ...

Having trouble retrieving the value of the second dropdown in a servlet through request.getParameter

I am facing an issue with storing the value of the second dropdown in a servlet after utilizing an ajax call in Java to populate it based on the selection made in the first dropdown. While I was able to successfully store the value of the first dropdown ...