自定义组件中的 connectedCallback() 是否可以根据使用上下文以不同方式进行解释?
Can connectedCallback() in a Custom Component be interpreted in different ways, depending on the context where it is used?
我创建了一个包含 Vue 实例的自定义组件:
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>
它工作正常独立(即 - 直接在浏览器中用作上面的代码片段)
然后我尝试将它添加到 Home Assistant,它提供了一种通过创建自定义元素来创建自定义卡片的方法,然后由 Home Assistant 显示。
在 Home Assistant 中使用相同的代码会导致 Vue 警告(实际上是错误):Cannot find element #app
我的问题如下:在某些情况下,我的自定义组件会根据使用位置的不同而呈现不同的情况吗?。附带问题是"if yes - is this normal and expected"
注意:我不想把它变成一个"Home Assistant"问题(这不是问它的正确地方)——而是想了解我是否write 可以被认为是 "self contained",一旦它在一个简单的 HTML 文件中工作,它应该可以在任何地方工作——或者自定义元素 content 是否仍然依赖/依赖于哪里使用此元素。 Home Assistant 恰好是这种行为差异发生的地方。
Vue 实例找不到 #app
。您可以将 card
元素直接传递给 el
。我使用了一个名为 vm
的变量稍后调用 vue 实例并将其附加到您的 DOM 和 vm.$el
.
试试这个:
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);
我创建了一个包含 Vue 实例的自定义组件:
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>
它工作正常独立(即 - 直接在浏览器中用作上面的代码片段)
然后我尝试将它添加到 Home Assistant,它提供了一种通过创建自定义元素来创建自定义卡片的方法,然后由 Home Assistant 显示。
在 Home Assistant 中使用相同的代码会导致 Vue 警告(实际上是错误):Cannot find element #app
我的问题如下:在某些情况下,我的自定义组件会根据使用位置的不同而呈现不同的情况吗?。附带问题是"if yes - is this normal and expected"
注意:我不想把它变成一个"Home Assistant"问题(这不是问它的正确地方)——而是想了解我是否write 可以被认为是 "self contained",一旦它在一个简单的 HTML 文件中工作,它应该可以在任何地方工作——或者自定义元素 content 是否仍然依赖/依赖于哪里使用此元素。 Home Assistant 恰好是这种行为差异发生的地方。
Vue 实例找不到 #app
。您可以将 card
元素直接传递给 el
。我使用了一个名为 vm
的变量稍后调用 vue 实例并将其附加到您的 DOM 和 vm.$el
.
试试这个:
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);