简体   繁体   English

如何在webpack中正确注入应用程序元素? -接收[Vue警告]:找不到元素:#app

[英]How to properly inject app element in webpack? - Receiving [Vue warn]: Cannot find element: #app

Here is my code code example 这是我的代码示例

I am trying to learn webpack 4 and am setting up a test project. 我正在尝试学习webpack 4,并正在建立一个测试项目。

Traditionally I have built vuejs app inside Asp.net websites. 传统上,我是在Asp.net网站内部构建vuejs应用的。 So I always know the entry html point and can put the element on the page. 因此,我总是知道html入口,可以将元素放在页面上。

From all the blog post I have seen for vue this seems to be all they do to setup their app. 从我看到的所有博客文章中,这似乎都是他们设置应用程序所要做的。

App.Vue App.Vue

<template>
    <div id='app'>
        <router-view></router-view>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class App extends Vue {

}
</script>

index.ts index.ts

import Vue from 'vue';
import App from './App.vue';
import router from './router';

Vue.config.productionTip = false;

new Vue({
  el: '#app',
  render: (h) => h(App),
  router
}).$mount('#app');

When I run this I get [Vue warn]: Cannot find element: #app. 运行此命令时,我得到[Vue警告]:找不到元素:#app。 If I add 如果我加

 document.write('<div id="app"><router-view></router-view></div>');

The code runs fine. 代码运行正常。 Since I am using vue-router, I don't think I actually need the App.vue file, but I still need someplace to mount the vue object too. 由于我使用的是vue-router,因此我认为我实际上不需要App.vue文件,但是我仍然需要某个位置来挂载vue对象。

So looking at my github link, what would be the correct way to get this working? 因此,看看我的github链接,什么是正确的方法?

This is a chicken-and-egg problem. 这是一个鸡与蛋的问题。 You're trying to amount the root component to the #app div, but the #app div exists inside the App component. 您正在尝试将根组件的数量分配到#app div中,但是#app div存在于App组件中。 At the time when you call new Vue the #app div doesn't exist because the App component hasn't mounted! 在您调用new Vue ,由于尚未安装App组件,因此#app div不存在!

Most Vue apps have an empty <div id="app"></div> in the index.html file so that the root Vue component has somewhere to mount to when the page has loaded. 大多数Vue应用程序在index.html文件中都有一个空的<div id="app"></div> ,以便在页面加载后,根Vue组件可以挂载到某个地方。

If you don't want to do it that way then you can mount it manually instead: 如果您不想这样做,可以改为手动安装:

const root = new Vue({
  render: (h) => h(App),
  router
}).$mount()

document.body.appendChild(root.$el)

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

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