Even in the absence of the element on the page, the VueJS instance is still being invoked

I am encountering an issue where all my VueJS instances are being executed, even if the element associated with them is not present on the page.

Currently, I have defined a mixin as follows:

var mixin = {
  methods: {
    listEvents(parameters) { 
      return axios.get('/api/v1/events', {params: parameters})
    },
    listLocations(parameters) { 
      return axios.get('/api/v1/locations', {params: parameters})
    },
  }
}

These mixins are used by multiple VueJS instances across different pages. Each page focuses on displaying either events or locations. The methods are stored in the mixin and then utilized by the specific instance created for that particular page, based on the presence of the specified element within it (e.g., id="locations" and el: "#locations").

Here's an example of one such instance:

// Vue
new Vue({
  el: '#locations',
  delimiters: ['[[', ']]'],
  mixins: [mixin],
  data: {
    locations: [],
    loading: true,
    error: false,
    page: 1,
    perPage: 20,
  },
  mounted: function () {
    console.log("VUEJS 'locations' has been mounted")
    this.init();
  },
  methods: {
    init() {
...
...

However, regardless of which page I am on, all instances seem to be triggered simultaneously. This results in unnecessary API calls, initialization of Leaflet maps without any container, creating chaos in the functionality.

Am I overlooking something crucial here or completely misinterpreting the behavior?

EDIT: It's worth noting that all instances are placed within `app.js`, which is included on all pages.

Answer №1

It seems like there is a script running on all pages that initializes new Vue objects, regardless of whether the elements they are attached to are actually displayed.

Even if the element being targeted by Vue does not exist, Vue will still create instances.

To address this issue, you can simply verify the existence of the elements before creating the Vue instance.

const locations = document.querySelector("#locations")
if (locations) {
  new Vue({
    el: "#locations",
    ...
  })
}

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

Ensure that the array of JSON objects is a subset of another array of JSON objects

I am looking to compare each array in testEdge with newarr and find the matching id for each array in testEdge const testEdge = [ [{ id: '0', from: '0', to: '1' }, { id: '1', from: '1&ap ...

Issue with logging objects in an array within a for loop

I am having an issue with a JavaScript for-in loop. Why does console.log(user) display the number "0" when iterating through users? Is it indicating the index of the user object in the array? I would like to log each object individually... Thank you r ...

vue.js watch function failing to update

Hello, I'm just getting started with Vue and currently facing a challenge. I am attempting to update a couple of variables based on changes in another computed variable. The computed variable is connected to a Vuex store and functions correctly, displ ...

Using an individual object instead of an array to create an autocomplete form

I am currently grappling with Vue JS as I embark on building my first Auto complete component using VueCLI. Below is the snippet of code that works fine when using an array: https://pastebin.com/a8AL8MkD filterStates() { this.filteredStates = this.stat ...

Looking for assistance on how to access a JSON file in JavaScript without the need for servers

As I embark on my journey with JavaScript, a question has been lingering in my mind - is it possible to access a JSON file locally, without the need for servers like WAMP? My goal is to simply retrieve the data from a JSON file and display its contents o ...

Improve the way you manage return statements

Here is the function in question: const checkifHaveBomb = (column, row) => { let isBomb = false activeBombContainer.forEach(element => { if (element.column === column && element.row === row) { ...

Why is my element still occupying space even though it has been hidden with a display of none?

Currently, I'm working on a dropdown navigation menu where one of the list items causes space issues when the display property is set to none. Specifically, the 'Book A Table' item isn't meant to be visible in the center div when the sc ...

Inserting a file read using Node.js into a MongoDB database

Recently, I came across a text file that contains the following data: title: A, alert: notice, desc: Starting title: B, alert: notice, desc: Process Step 1 and 2 Step 1 - Execute Step 2 - Log title: C, alert: notice, desc: "Ending" My goal is to insert ...

Monitor the closure of a programmatically opened tab by the user

Currently, I am in the process of developing a web application using Angular 11 that interacts with the msgraph API to facilitate file uploads to either onedrive or sharepoint, and subsequently opens the uploaded file in the Office online editor. Although ...

I'm encountering a 404 error with Jquery ajax, indicating that the requested resource was not

Check out the code snippet below: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/ ...

Creating a unique icon using Jquery Mobile for a button in a PhoneGap application

Has anyone experienced issues with using a custom icon for a jQuery mobile button? I am having trouble as it is only showing a grey circle instead of the actual icon. The default icons work fine, though. Here is the code snippet from the index.html page: ...

What is the best way to transfer values or fields between pages in ReactJS?

Is there a way to pass the checkbox value to the checkout.js page? The issue I'm facing is on the PaymentForm page, where my attempts are not yielding the desired results. Essentially, I aim to utilize the PaymentForm fields in the checkout.js page as ...

Jquery ajax is failing to achieve success, but it is important not to trigger an error

My jQuery ajax request seems to be stuck in limbo - it's not throwing an error, but it also never reaches the success function. This is how my code looks: function delete() { $("input[name='delete[]']:checked").each(function() { ...

Donut and Bar Graph by Highchart

My goal is to create a chart similar to the one shown in the Example Image linked below. I have provided two separate plunkers for each type of chart. What I am aiming for: Example Image Donut Chart: ===> Refer to Comment section for Plunkr link // ...

Discover which sub package is needed by running Npm check

While executing the command npm install, I encountered this error message: The package "getSnapshot-pkg-repo@^1.0.0" required by "conventional-changelog-core@^2.0.11" could not be found on the "npm" registry. I am uncertain about the source of this i ...

The initial transition in offcanvas on bootstrap 5 is not appearing when a placement is dynamically added

I am currently working on triggering an Offcanvas with JS and making the placement configurable. The issue arises when attempting to dynamically set the offcanvas-end class to the offcanvas element, as it does not transition smoothly the first time it is t ...

Received an error in Vue3 using the Composition API, Vuex4, and TypeScript, stating that the store

I recently transitioned a personal project from Vue2 to Vue3, but I've encountered an error that has me stumped. Despite my efforts to fix it by searching various threads and documentation on different sites, nothing seems to be working or getting me ...

Tips for ensuring synchronous state changes in React

I am working on a currency calculator using react.js I am fetching the latest exchange rates and storing them in state using the getRates function: getRates(currencyShortcut){ fetch('https://api.fixer.io/latest?base='+currencyShortcut) ...

React child component does not refresh upon modification of an array property

In my main application, I have two subcomponents that both receive the same model property. The first subcomponent deals with a number prop from model.myNumberProperty, and the second subcomponent handles an array prop from model.myArrayProperty. When ch ...

What is the best way to handle form data for JSON manipulation in jQuery?

var checkedValues = $('.required:checked').map(function () { return this.value; }).get(); var arr = new Array(10); alert(checkedValues); alert("number of values in it " +checkedValu ...