简体   繁体   English

为什么我的 Vue 本地组件没有出现在页面中?

[英]Why is my Vue local component not appearing in the page?

I am learning Vue and messing around with examples in their guide.我正在学习 Vue 并在他们的指南中使用示例。 I am trying to register a sub-component locally inside a root vue component as described here.我正在尝试在根 vue 组件中本地注册一个子组件,如此处所述。 But it does not appear on my page.但它没有出现在我的页面上。 What am I missing ?我错过了什么? app.components also returns undefined. app.components 也返回 undefined。

 console.log('Loading my script'); var componentX = { template: `<h3>Hello</h3>` } var app = new Vue({ el: '#vue-div', template: `<div>Vue is working</div>`, components: { 'component-x': componentX } }) console.log(app.components);
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <div id="vue-div"> <component-x></component-x> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script> <script src="./js/test.js"></script> </body> </html>

The issue is, your main Vue has a template - this replaces any HTML inside the target element问题是,你的主 Vue 有一个模板——它替换了目标元素内的任何 HTML

So, you can either add the component-x inside the new Vue constructor template:因此,您可以在新的 Vue 构造函数模板中添加component-x

 console.log('Loading my script'); var componentX = { template: `<h3>Hello</h3>` } var app = new Vue({ el: '#vue-div', template: `<div>Vue is working<component-x></component-x></div>`, components: { 'component-x': componentX } }) console.log(app.$options.components);
 <div id="vue-div"></div> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script> <script src="./js/test.js"></script>

Or you can remove the template: from the new Vie constructor and the existing content of the target element will be used或者您可以删除模板:从新的 Vie 构造函数中,将使用目标元素的现有内容

 console.log('Loading my script'); var componentX = { template: `<h3>Hello</h3>` } var app = new Vue({ el: '#vue-div', components: { 'component-x': componentX } }) console.log(app.$options.components);
 <div id="vue-div"> Vue is working <component-x></component-x> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM