Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance Vue if element exists?

Tags:

vue.js

I'm building an app that a page has some vms, in others not. When we change from one page to another show the following warning:

[Vue warn]: Cannot find element: #element-id

How do I instantiate VMs only if there is the element on the page and avoid the error?

NOTE: I'm using Rails asset pipeline, so, all the javascript is concatenated into a single file.

like image 559
Alexandre Magro Avatar asked Jun 18 '16 20:06

Alexandre Magro


People also ask

How do you know if an element is present?

In order to check if an element is present on a webpage, we make use of driver. findElements() method. As we know that driver. findElements() method returns a list of webElements located by the “By Locator” passed as parameter.

How do I know if an element has a DOM?

contains DOM API, you can check for the presence of any element in the page (currently in the DOM) quite easily: document. body. contains(YOUR_ELEMENT_HERE);

What is $El in Vuejs?

The $el option in Vue provides Vue with an existing HTML element to mount the Vue instance generated using the new keyword. this. $el. querySelector is used to access HTML elements and modify the element's properties.

What is Vue component instance?

One important feature of Vue is the ability to use components. Components are reusable Vue instances with custom HTML elements. Components can be reused as many times as you want or used in another component, making it a child component. Data, computed, watch, and methods can be used in a Vue component.


1 Answers

There are no issues just leaving it as is. This is just a warning that only runs when debug mode is on, so you should have it turned off in production anyway.

If you want to get rid of it, just check if the element exists before launching Vue -

if(document.getElementById("element-id")){
  new Vue({...})
}

Ref: How to check if element exists in the visible DOM?

like image 194
Jeff Avatar answered Sep 23 '22 15:09

Jeff