通过webpack创建完Vue项目(创建vue-router)后的项目结构如下:
内容介绍:
项目运行
项目的运行入口:index.html
为什么index.html是项目的入口以及为什么index.html加载后会继续加载main.js、App.vue、index.js,以及他们之间的关系是如何联系起来的呢,这块的配置文件位于build文件夹下,包括webpack.dev.conf.js等,感兴趣的可以了解下。通过项目的配置文件,可以加载运行我们的index.html文件以及自动关联vue相关的模块。
一、index.html中的内容:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>test</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
在body体中只有一个div标签,其id为app,这个id会连接到src/main.js内容。
二、main.js中的主要的代码
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
在main.js中,新建了一个vue实例,并使用el:#app链接到index.html中的app,并用template引入组件<app>和路由相关的内容。也就是说通过main.js我们关联到App.vue组件。
三、App.vue中的主要的代码
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
App.vue中的内容,是一个标准的App.vue模板的形式,包含了<template></template>、<script></script>、<style></style>三部分,从template标签中可以看到,使用img标签加载了vue的图像,也就是我们使用npm run dev运行vue项目后看到的图像,那么图像下面的内容是从哪里渲染出来的呢?
可以注意到,<template>标签下,除了<img>标签外,还有<router-view>标签,<router-view>标签将会把路由相关内容渲染在这个地方,接下来,我们看一下路由的内容有哪些,在哪里出现的。其实,这个文件位于src/router/index.js中。
四、index.js中的主要的代码
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}
]
})
在index.js的代码中,建立了路由相关的内容,也就会渲染到app.vue下面的<router-view>中。在index.js中,将HelloWorld组件发布为路由,换句说,index.js在这里就是将HelloWorld发布为路由,以在图片下面进行展示HelloWorld内容,接下来我们再看看components/helloword中的内容是啥(由于里面的内容比较多,这里对HelloWorld组件进行了删减)。
五、HelloWorld.vue中的主要的代码
<template>
<div class="hello">
<hr>
<h1>{{ msg }}</h1>
<hr>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'HelloWorld\'s components'
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
在HelloWorld.vue的template中,我们可以看到界面上渲染的一些连接等内容。到此,这个页面的加载渲染过程结束了。
总结
通过上述过程,我们可以看到项目加载的过程是index.html->main.js->app.vue->index.js->HelloWorld.vue。这里只是对运行项目后,如何出现首页面做简单解释,具体实现没有进行分析。