昨天学习了vue的组件之后想自己开发一个博客的前端,由于是第一个项目,先不用ivew库,自己造个轮子。
Layout 包括博客的 Header 和 Footer ,这两个组件是所有的页面都有的公共模块,放在跟组件App.vue里, props部分包括 用来切换主题的 theme,大标题,作者信息等。
在为Header 嵌入logo 图片的时候,发现直接在 data里用 log: '../assets/log.jpg'
不能引用到图片地址,得这样写。
//html部分
<img class = 'logo' :src = "logo"></img>
//script部分
data(){
return {
log: require('../assets/log.jpg')
}}
这里的require 把 相对地址转换成绝对地址。
主页中的侧边栏只有两级菜单,用两个列表渲染完成。
中间的文章内容通过一个列表循环来完成。
文章的标题应该有跳转到查看博客细节的页面,通过blog的ID来实现。
<router-link class='head' :to="'blog/'+ item.id">{{ item.title }}</router-link>
router定义录下,通过/:id
传递query参数。
export default new Router({
routes: [
{
path: '/index',
name: 'index',
component: Index
},
{
path: '/blog/:id',
name: 'blog',
component: BlogDetail
}
]
})
重点在博客详情页,通过ajax操作向后端请求数据。梳理一下我在这一步掉进了多少坑。
由于vue本身并不支持发送ajax请求,首先要安装vue-resource模块(vue2.0建议用axios, 并且已经停止了对vue-resource的更新,有机会再来踩这个坑)。
$cnpm install --save vue-resource
另外要安装json-server模块,这是一个Node模块,运行Express服务器,可以指定一个json文件作为api的数据源,和nosql很相似的样子,支持跨域、jsonp、路由定制、快照保存等功能。它提供过滤查询,分页查询,排序,切片,实体关联,全文检索等高级功能。
$cnpm install --save json-server
然后在项目根目录下创建一个db.json文件,比如这样
{
"blogdetail" :[
{"id": 1, "title":"第一篇博客", "content":"这是地一篇博客的内容,从db.json中提供", "timestamp":"2019-04-01"},
{"id": 2, "title":"第二篇博客", "content":"这是地二篇博客的内容,从db.json中提供", "timestamp":"2019-04-02"}
],
"user":
[
{"id":1, "name":"crispto", "pwd":"password"}
]
}
除此之外还需要做一些配置。
在build/webpack.dev.conf.js中添加这一段。
/*----------------jsonServer---------*/
/*引入json-server*/
const jsonServer = require('json-server')
/*搭建一个server*/
const apiServer = jsonServer.create()
/*将db.json关联到server*/
const apiRouter = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
apiServer.use(middlewares)
apiServer.use(apiRouter)
/*监听端口*/
apiServer.listen(3000, () => {
console.log('JSON Server is running')
})
在config/index.js中的 proxyTable中添加路由代理(注意proxyTable在文件中本来就存在的,默认为空)
proxyTable: {
'/api': {
changeOrigin: true,
target: 'http://localhost:3000',
pathRewrite:{
'^/api':''
}
}
}
这个代理配置会将项目里所有已/api
开头的 url 转换成 localhost:3000 。
重启服务,可以看到json-server服务已经在3000端口启动了,用浏览器打开就可以看到Congrats!的页面。
为了让BlogDetail能够在创建的时候就动态获取内容,在BlogDetail组件script中添加ajax代码。
created:function(){
this.id = this.$route.params.id
this.getBlogDetail(this.id)
console.log(this.blog)
},
methods: {
getBlogDetail(id){
this.$http.get('/api/blogdetail/' + this.id)
.then((res)=>{
this.blog=res.data
//注意这里data居然是一个对象而不是字符串,我连反序列化都不用做,直接在template里就能引用 blog.title等属性。
}, (err) =>{
console.log(err)
})
}
}
这里我刚开始犯了一个错误,把created 作为一个method 放在methods下面了,结果当然加载不到数据, 实际上它作为vue实例的一个constructor,和methods是平级的属性。另外就是get方法有两个回调函数,一个是自带参数res, 一个自带参数err, 如果成功,执行第一个,出错则执行第二个。两个函数都是用箭头定义的匿名函数。
到这里还有一个大坑,系统显示get属性undefined!
原来vue-source包还没有被注册。需要在App.vue里加上这一句
import VueResource from 'vue-resource'
Vue.use(VueResource)
到这里为止,程序才跑通了,可以在index中通过点击文章标题跳转到文章页面并能动态加载数据。
工程现状: