Is it possible for the connectedCallback() method within a Custom Component to have varying interpretations based on the specific context in which it is implemented?

I have recently developed a Custom Component that incorporates a Vue instance:

class ContentCardExample extends HTMLElement {
  connectedCallback() {
    const card = document.createElement('div');
    card.setAttribute("id", "app")
    card.innerHTML = 'hello is {{hello}}'
    this.appendChild(card);
    new Vue({
      el: "#app",
      data: {
        hello: 5
      }
    })
  }
}

customElements.define('content-card-example', ContentCardExample);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<content-card-example></content-card-example>

This component functions perfectly individually (as shown in the code snippet above directly in a web browser)

However, when I attempted to integrate it into Home Assistant, which allows for customized cards through a Custom Element displayed by Home Assistant, I encountered a Vue warning (essentially an error): Cannot find element #app

My query now is: Are there scenarios where my Custom Component renders differently based on its usage environment?. This leads to the related question of whether this behavior is normal and expected.

Note: I do not wish to focus on "Home Assistant" specifically (as this may not be the appropriate forum) - but rather understand if this component can be considered "self-contained" and should work universally once functional in a basic HTML file, or if a Custom Element's content still relies on and is influenced by its implementation location. In this case, Home Assistant showcased variations in behavior.

Answer №1

If the Vue Instance is having trouble locating the #app element, you can directly pass your card element to el. To do this, create a variable named vm and use it to call the Vue instance later on. You can then append it to your DOM using vm.$el.

Give this a try:

class ContentCardExample extends HTMLElement {
  connectedCallback() {
    const card = document.createElement('div');

    card.innerHTML = 'hello is {{hello}}';

    const vm = new Vue({
      el: card,
      data: {
        hello: 5
      }
    });

    this.appendChild(vm.$el);
  }
}

customElements.define('content-card-example', ContentCardExample);

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

How can you prevent a draggable element from surpassing the bottom of the screen?

I'm dealing with an element that I want to make draggable only along the Y-axis. It needs to be able to go past the top of the screen, but I need to restrict it from going past the bottom of the screen. I recently came across the containment feature i ...

Inquiring about the intricacies of using Regular Expressions in

Can anyone provide a regex that only allows the characters 0-9, a-z, A-Z, hyphen, question mark, and "/" slash, with a character length between 5 to 15? I attempted the following approach, but it did not yield the desired result: var reg3 = /^([a-zA-Z0-9? ...

The concept of asynchronicity and callbacks in JavaScript

As a newcomer to the world of JavaScript and Stack Overflow, I have been learning about synchronous, asynchronous, and callbacks through various videos and blogs. However, I still have a lingering doubt. If synchronous code means following a sequential ord ...

What is the process of mapping an array of object IDs in order to retrieve the corresponding objects associated with each ID

I currently have a specific collection that stores IDs referencing objects in a separate schema. If I'm working with an array containing these IDs, what is the best way to iterate through and retrieve the corresponding object? Although I've mad ...

How can you use a single parameter in a JavaScript function to swap the values of two numbers

Here's the challenge I'm facing: I need to create a function that will output 5 when given a(0), and 0 when given a(5). a(0) = 5 a(5) = 0 It should look like this: Hint: Use the following function structure function A(num){} something ...

Issue with binding Vue v-model to input element in Parent component is not functioning as expected

Utilizing Vue, Nuxt, and Vue Good Table to implement live searching on a table has presented a challenge for me. I created a child component called child.vue and imported it into the parent page named parent.vue. To bind the searchTerm with the input eleme ...

I can't quite understand the reasoning behind why this specific function is designed to output

I've been working on a JavaScript exercise and struggling to understand the logic behind it. The exercise involves a function named "mystery" that utilizes several basic functions to return an array in reversed order. Despite spending hours trying to ...

ReactJS does not update the conditional CSS class when hovering with mouseOnEnter or mouseOnOver

I am currently attempting to showcase data in a table where each row features an info icon that is only visible upon hovering. Additionally, I want a pop-up to appear when the info icon is clicked (there is an onclick function assigned to this button). He ...

Unspecified origins of Js in Chrome Extension

console.log(chrome.runtime.sendMessage({from:"script2",message:"hello!"})); However, attempting to send the message from a background script to a content script is proving to be unsuccessful. https://i.stack.imgur.com/ERgJB.png ...

Reimagining the Vite proxy server functionality

/** * Function to create a list of proxies based on prefixes defined in .env.development * @param list */ export function generateProxies(list: ProxyList = []) { const result: ProxyTargetList = {}; for (const [prefix, target] of list) { const i ...

Utilizing analytics.js independently of the react-ga library

Is there a way to integrate Google Analytics into my React app without using the react-ga package? I specifically want to access the ga function in a separate JavaScript file as well as within a React component. How can I achieve this by importing the anal ...

Scheduled Job unable to complete post request

(I am completely new to the world of JavaScript, node.js, and Heroku so I apologize in advance if my question is not very clear) I recently set up a Heroku node.js application with a scheduled task that should run every hour. The task does run as expecte ...

The mousedown event handler in Three.js disrupts the focus on the input field

Here is a line of code in threejs: document.addEventListener('mousedown', onDocumentMouseDown, false); This particular code snippet causes the input field to lose focus when clicked. This can be problematic, for instance, when there is a canva ...

Leveraging colons in the process of object destructuring

I'm still trying to wrap my head around all the wonders of ES6. Ran across this snippet in an online article and I'm puzzled by how PrivateRoute is deconstructing the input props. What exactly is the purpose of component: Component here? const P ...

Is it possible to trigger JavaScript after loading a page in jqTouch with AJAX?

Similar to the kitchensink demo, I have successfully used jqtouch to call external .html pages into the index page. One of these external pages contains a video that is being played using sublime player. Everything is pretty basic so far, but my challenge ...

Increase value by 1 with the push of a button within two specified ranges using JavaScript

I am looking to create buttons that will increase the value of both the first and second range by 1 when pressed, as well as decrease the value of both ranges by 1 when pressed. Here is my code: function run(){ var one = document.getElementById("rang ...

Using regular expressions in Javascript to extract decimal numbers from a string for mathematical operations

I'm currently working on a Vue method where I extract information from a WordPress database. The data retrieved sometimes contains unnecessary text that I want to filter out. Using the prodInfo variable, the input data looks something like this: 2,5k ...

Unveiling concealed content with JQuery

Here is a link to my pen: http://codepen.io/anon/pen/IszKj I am looking to achieve the functionality where clicking on either "any status" or "any date" will reveal a hidden div containing a list of options. My main query is about the best approach to ta ...

Is there a way to dynamically include an attribute using VueJS?

Is there a way in Vue to dynamically add an attribute, not just the value of an attribute using v-bind? I am aware that I can set a value to an attribute dynamically with v-bind, but I would like to add the attribute itself based on a condition. Something ...

Preserve the XHR-generated configuration when the browser is refreshed

My PHP page features a navigation menu with options such as Home, About Us, and Profile. When clicking on the "About Us" link from the home page, it loads an Ajax response displaying the information without reloading the page. However, if the user decide ...