新人,刚开始学习 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 里面的内容会没有生成,我觉得是模板指向之类的问题错了,但是搜了很久也想不到原因,请各位指点下。
咦~,你这个自然是不会显示的啦,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实例化的各个选项、单文件组件。