返回
记录Vue+ThinkJS博客程序的开发历程
前端
2023-10-22 05:42:43
一入冬懒癌发作,给自己找点事干。之前博客程序写过几次,php的写过两次,nodejs用ThinkJS写过,随着ThinkJS版本从1.x升级到2.x之前的博客程序也做过升级。但是因为前面考虑搜索引擎抓取还是选用了php的ThinkPHP,这回换用Vue+ThinkJS组合尝试下,只用nodejs。
1. 环境搭建
先初始化项目,这里省略步骤,直接上结果:
"dependencies": {
"axios": "^0.19.2",
"bootstrap": "^4.3.1",
"jquery": "^3.4.1",
"popper.js": "^1.14.7",
"vue": "^2.6.11",
"vue-router": "^3.1.3",
"vuex": "^3.1.2"
},
"devDependencies": {
"@babel/core": "^7.9.6",
"@babel/preset-env": "^7.9.6",
"babel-loader": "^8.1.0",
"css-loader": "^3.6.0",
"html-webpack-plugin": "^4.5.0",
"style-loader": "^1.2.1",
"vue-loader": "^15.9.3",
"vue-template-compiler": "^2.6.11",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}
启动服务:
"scripts": {
"dev": "webpack-dev-server --open --hot",
"build": "webpack --mode production"
}
测试通过后进行打包。
2. 后端ThinkJS开发
ThinkJS的安装,这里就不做详细介绍了。安装好后,可以在控制台运行命令tp5 help
查看帮助信息。ThinkJS框架与ThinkPHP框架在使用上有许多相似之处。但是ThinkJS更加轻量级,并且支持前后端分离。
新建一个博客项目,目录如下:
├── app
├── config
├── public
├── runtime
├── thinkphp
└── vendor
在app
目录下新建一个控制器IndexController.js
,代码如下:
module.exports = class extends think.Controller {
async indexAction() {
let posts = await this.model('post').select();
this.assign('posts', posts);
return this.display();
}
};
在app/model/post.js
中定义数据模型:
module.exports = class extends think.Model {
async indexAction() {
return await this.select();
}
};
在config/route.js
中配置路由:
module.exports = [
['GET /', 'index/index'],
['GET /post/:id', 'index/post']
];
3. 前后端整合
ThinkJS框架支持前后端分离,因此我们可以使用Vue.js作为前端框架。在public/js
目录下新建一个文件app.js
,代码如下:
import Vue from 'vue'
import App from './App.vue'
new Vue({
el: '#app',
render: h => h(App)
})
在public/index.html
中引用app.js
文件:
<script src="js/app.js"></script>
这样,我们就完成了Vue+ThinkJS博客程序的开发。
4. 项目部署
将项目部署到服务器上,这里可以使用Nginx作为Web服务器。在Nginx的配置文件中添加如下配置:
server {
listen 80;
server_name www.example.com;
root /var/www/blog;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
然后重启Nginx服务,项目就可以正常运行了。
5. 总结
本文记录了使用Vue+ThinkJS开发博客程序的整个过程。希望对有兴趣使用Vue+ThinkJS开发博客程序的读者有所帮助。