vue+vue-router+axios+element-ui构建vue实战项目之四(修改App.vue、router和page文件)

在上一篇《vue+vue-router+axios+element-ui构建vue实战项目之三(解读项目文件)》中,我们认识了项目中各文件夹和文件的作用,并且重新整理了一下,如果忘记了的朋友,不妨再去看一下。

那么这篇文章,我们就来修改下项目中的App.vue和router文件的内容,让项目能够重新运行起来。

修改App.vue文件

先把默认的代码删掉部分,改成这样:

 1 <template>
 2   <div id="app">
 3     <router-view></router-view>
 4   </div>
 5 </template>
 6 
 7 <script>
 8 export default {
 9   name: 'App'
10 }
11 </script>
12 
13 <style lang="scss">
14   @import "./style/style";
15 </style>

样式引用src/style/style.scss文件,因此在App.vue文件中,按照这样@import "./style/style"引用。

<style lang="scss">表示可以编写或导入scss、sass、css文件。

引用scss文件时,可以省略.scss后缀。

更多关于sass的内容,可以学习阮一峰的《SASS用法指南》。

既然,我们引入了scss文件,就需要能够编译的工具,接下来我们需要下载两个包工具,在终端输入:

1 npm install -D node-sass sass-loader

由于网络原因,我使用了cnpm下载:

修改router文件

目前,修改工作只进行了一部分,现在npm run dev是运行不了项目的,还需要我们修改router/index.js路由文件

这是修改之前的代码:

 1 import Vue from 'vue'
 2 import Router from 'vue-router'
 3 import HelloWorld from '@/components/HelloWorld'
 4 
 5 Vue.use(Router)
 6 
 7 export default new Router({
 8   routes: [
 9     {
10       path: '/',
11       name: 'HelloWorld',
12       component: HelloWorld
13     }
14   ]
15 })

根据我们目前的目录,代码修改如下:

 1 import Vue from 'vue'
 2 import Router from 'vue-router'
 3 import index from '@/page/index'
 4 import content from '@/page/content'
 5 
 6 Vue.use(Router)
 7 
 8 export default new Router({
 9   routes: [
10     {
11       path: '/',
12       name: '首页',     //path别名,可删除
13       meta:{
14         title: '首页'   //设置页面title
15       },
16       component: index
17     },
18     {
19       path: '/content/:id',
20       name: '详情',
21       meta:{
22         title: '详情'
23       },
24       component: content
25     }
26   ]
27 })

path:‘/’ 就是默认首页,也就是index页面。

这里'/content/:id',我们这里使用了动态路由匹配, :id 就是各内容页面的ID, 例如‘/content/10’、‘/content/20’这种。

更多关于动态路由的知识,可以参阅官方文档《动态路由匹配》。

好了,路由配置也完成了,接下来只剩最后一步,给页面添加内容了。

index.vue和content.vue文件添加内容

index.vue文件:

 1 <template>
 2     <div>index page</div>
 3 </template>
 4 <script>
 5     export default {
 6 
 7     }
 8 </script>
 9 <style lang='scss'>
10     @import '..style/style'
11 </style>

content.vue文件:

 1 <template>
 2     <div>content page</div>
 3 </template>
 4 <script>
 5     export default {
 6 
 7     }
 8 </script>
 9 <style lang='scss'>
10     @import '..style/style'
11 </style>

好了,简单的页面内容有了,具体的内容后续再添加。

现在我们在终端输入:

npm run dev

短暂的编译成功后,终端显示:

在浏览器输入 http://localhost:8080,我们看到的内容:

接着我们输入 http://localhost:8080/#/content/10,如下:

 

OK,基本的配置完成,下一节我们将学习如何在项目中配置Axios。

如果文章中存在错误的地方,麻烦请大家在评论中指正,以免误人子弟,谢谢!
原文地址:https://www.cnblogs.com/zhaoyongblog/p/10383533.html