写在前面
为了解决后端人员不足又招聘不到的问题,决定用前后端分离的方式写项目,于是尝试用django-rest-framework
跟Vue.js
搭建一个项目。
基础搭建项目的参考了一下教程使用Django + Vue.js快速而优雅地构建前后端分离项目
整体来说教程写的还可以,但是实际搭完之后,其实还是有很多问题需要解决。
首先,看一下我搭建的前端跟项目的结构。
结构
web pack.config.js
var path = require('path')
var webpack = require('webpack')module.exports = {entry:{build:'./src/main.js',index:'./src/index.js',foot:'./src/foot.js',login:'./src/login.js',about_us:'./src/about_us.js',sideList:'./src/sideList.js',},output: {path: path.resolve(__dirname, './dist/'),publicPath: '/dist/',filename: 'static/js/[name].js'},module: {rules: [{test: /\.vue$/,loader: 'vue-loader',options: {loaders: {// Since sass-loader (weirdly) has SCSS as its default parse mode, we map// the "scss" and "sass" values for the lang attribute to the right configs here.// other preprocessors should work out of the box, no loader config like this necessary.'scss': 'vue-style-loader!css-loader!sass-loader','sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'}// other vue-loader options go here}},{test:/\.css$/,loader:'style-loader!css-loader'},{test: /\.js$/,loader: 'babel-loader',exclude: /node_modules/},{test: /\.(png|jpg|gif|svg)$/,loader: 'file-loader',options: {name: 'static/img/[name].[ext]?[hash]'}}]},resolve: {alias: {'vue$': 'vue/dist/vue.esm.js'}},devServer: {historyApiFallback: true,noInfo: true},performance: {hints: false},devtool: '#eval-source-map'
}if (process.env.NODE_ENV === 'production') {module.exports.devtool = '#source-map'// http://vue-loader.vuejs.org/en/workflow/production.htmlmodule.exports.plugins = (module.exports.plugins || []).concat([new webpack.DefinePlugin({'process.env': {NODE_ENV: '"production"'}}),new webpack.optimize.UglifyJsPlugin({sourceMap: true,compress: {warnings: false}}),new webpack.LoaderOptionsPlugin({minimize: true})])
}
我把Django的static文件直接指向了dist.
在settings.py中设置。STATIC_URL = '/fontend/dist/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, "../fontend/dist/static")
Vue实现单页面渲染,把单个页面的css都压缩到js中,index.html页面代码直接引用一个js即可。
<body><div id="app"></div><script src="/dist/static/js/index.js"></script>
</body>
有个问题需要解决,就是这种目录结构下,vue的根目录是从dist
开始,索引不到fontend
,
而django
是从fontend
开始,所以上述路径/dist/static/js/index.js
,vue是可以访问到的,而django访问不到,想让django访问到,就在访问静态文件时改写静态文件的路径。在urls.py中加入这样一行
from django.views.static import serve
from mainsys import settingsurl(r'^(?P<path>.*)$', serve, {'document_root': settings.DOCUMENT_ROOT, 'show_indexes': True}),
其中settings.py设置。DOCUMENT_ROOT = os.path.join(BASE_DIR, 'fontend/')
先写这么多,以后遇到坑的时候再更新。