为何我的 vue 实例已经创建了,但是页面上却什么都没有显示?

新人,刚开始学习 vue + webpack,一步步自己搭建。运行页面后,编译没有报错,页面也没有报错,貌似 vue 实例已经成功创建了。index.html 里的 <div id="app"></div> 不见了,应该是被替换掉,但是页面却显示空白,想不明白,请教各位:

<head>
    <link rel="stylesheet" href="http://10.0.0.2:111/styles/com.css">
</head>
<body>
    <div id="app"></div>
    <script src="http://http://10.0.0.2:111/scripts/build.js"></script>
</body>

上面是 index.html

<template>
    <div id="app"></div>
</template>
<script>
    export default {
        name: "app"
    }
</script>
<style scoped></style>

上面是 App.vue

import Vue from 'vue';
import router from './router';
import store from './store';
import App from '../../../components/App.vue';
new Vue({
    el : '#app',
    router,
    store,
    components : {App},
    template : "<App/>",
    created(){
        this.$router.push({name : "index"});
        console.log("create", this);
    },
});
<template>
    <div>{{ name }}</div>
</template>
<script>
    export default {
        data () {
            return{
                name : "hellow",
            }
        },
        created () {
            console.log("index", this);
        },
    }
</script>
<style scoped></style>

上面是 index.vue

import Vue from 'vue';
import VueRouter from 'vue-router';
import index from '../../../../components/index.vue';
Vue.use(VueRouter);
const routes = [{path : "/index" , name :"index" , component : index},];
export default new VueRouter({routes})

前面漏了 router 配置,现在补上。

结果实际页面上显示的是:

<head>
    <link rel="stylesheet" href="http://10.0.0.2:111/styles/com.css">
</head>
<body>
    <!--function(e,n,r,o){return Oe(t,e,n,r,o,!0)}-->
    <script src="http://http://10.0.0.2:111/scripts/build.js"></script>
</body>

控制台里输出了 “created” 那句话,没有输出 “index", 我就想不明白了,不报错的话,为什么 index.vue 里面的内容会没有生成,我觉得是模板指向之类的问题错了,但是搜了很久也想不到原因,请各位指点下。

阅读 22.1k
6 个回答

咦~,你这个自然是不会显示的啦,Index.vue都没有在任何地方被引入,怎么会出现呢?
你要在App.vue文件中使用这个组件的话,两种方式。
第一种,单独把这个文件引入到App.vue,并且加入components选项中,然后在template模板中使用。
第二种,在App.vue中使用router-view组件,并在router/index.js中加入路由映射。看到你的例子中,在Vue根实例中调用$router.push,那么这里有3个问题。1.没有在根实例模板使用router-view 2.没有在router/index.js中注册路由 3. 通常是不在new Vue里这么干啦。先使用vue-cli创建一个demo看看吧。

对于上面的第一种方式,使用vue-cli 3.0,创建一个demo,看里面的HelloWorld.vue和App.vue文件就明白了。
建议先了解一下Vue实例化的各个选项、单文件组件。

你的webpack.config 配置的问题,你的vue引用错了,请参考 vue-cli别名配置,你的模板是无效的。
在你的webpack.config 加入下面这段代码:
resolve: {

    alias: {
     'vue$': 'vue/dist/vue.esm.js',
    }
  },

路由配置了没,或者直接在app组件里引用index组件试试

1.App.vue里没有<router-view>

<div id="app">
  <router-view></router-view>
</div>

2.没试过把route写在main.js, created的时候app还没渲染出来

const router = new VueRouter({
  routes: [
    { path: '/', name: 'index', component: index }
  ]
})

package.json 里面的入口文件里写的啥..

不如你把代码上传到github之类的网站, 大家才知道你错哪

新手上路,请多包涵

我得是路径写错了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题