
2、App.vue
通过入口文件中做的事情,我们其实已经知道 App.vue 的作用了:单页面应用的主组件。所有页面都是在 App.vue 下通过路由进行切换的。所以,我们可以理解为所有的路由(route)也是 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>node 之所以可以识别出 *·vue 格式的文件,是因为 webpack 在编译时将 *.vue 文件中的 html 、js 、css 都抽出来形成新的单独文件。可通过 npm run build 命令编译源代码,查看 dist 文件下的文件来验证。
App.vue 的内容分为三个部分:<template>...</template>、<script>...</script>、<style>...</style> ,分别在这三类标签里面写入结构、脚本、样式。
我们先从 <template> 看起:里面一个 div 包裹着 img 标签和 router-view 标签。前面提到过: App.vue 是单页面应用的主组件。对照着前面在浏览器中打开的应用主页面,img 标签就是页面上方的 Vue 的 logo。那下面的内容去哪了呢?和 <router-view/> 有关系吗?这就要去看路由了。
3、router/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,
},
],
});前面先引入了路由插件 vue-router,然后显式声明要用路由 Vue.use(Router) 。路由的配置非常地明了:给不同 path 分配不同的组件(或者页面),参数 name 只是用来识别。
当我访问根路由 http://localhost:8080/#/ 时,App.vue 中的 <router-view/> 就会把引入的 HelloWorld 组件分配给我,放在了 img 标签的下面,打开 components 目录下的 HelloWorld.vue 就可以看到具体内容了。
url 的时候会觉得奇怪,为什么在后面加了一个 # 号呢?这是因为 vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,当 URL 改变时,页面不会重新加载。详见:https://router.vuejs.org/zh/guide/essentials/history-mode.html。这里可先跳过这点内容。
现在,我们在浏览器访问 http://localhost:8080/#/vue 这个地址,会发现只出现了 Vue 的 logo。这是因为我们并没有配置 /vue 这个路由,找不到路由,那<router-view/> 这个标签就不会加载出来。
到这里,我们就知道路由是如何根据 url 来分配不同的组件了。配置多个路由就很简单了:
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/about',
name: 'about',
component: About
},
{
path: '/vue',
name: 'vue',
component: Vue
}
]
})那如果要访问 http://localhost:8080/#/vue/demo 怎么办呢?
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
},
{
path: '/about',
name: 'about',
component: About,
},
{
path: '/vue',
name: 'vue',
component: Vue,
children: [
{
path: '/demo',
component: demo,
},
{
path: '/project',
component: project,
},
],
},
],
});给路由加多一个子路由配置即可。
4、assets
用来存放一些图片、样式等静态文件。
三、总结

