vue-router默认是需要将项目放在服务器的根目录下的, 在浏览器里输入域名是这样:

http://mydomain.com/

vue怎么确认去服务器取数据还是在本地取数据呢? 其实借助的是井号"#", 井号在url中指向的是自己, 而不会去服务器取数据. 如下url, 是在根目录下的vue应用中, 也就是在vue-router中被导航.

http://mydomain.com/#/login

而如下url,将会到服务器上去取数据

http://mydomain.com/login

但如果要放置在子目录下呢, vue应用放在productinfo目录中:

http://mydomain.com/productinfo/#/login

需要两步:
1. 需要配置 router的config:

const RouterConfig = {
    base: 'productinfo'
};
const router = new VueRouter(RouterConfig);
  1. vue-router一般都是用vue-cli或者webpack, 做多个文件打包的, 也就是运行:

    npm run build

可以打包app. 当然, package.json中需要有对应的build配置, 如下:

  "scripts": {
    "build": "webpack --progress --hide-modules --config webpack.prod.config.js",
  },

那么在webpack.prod.config.js中, 也需要配置路径, 否则默认应用的打包文件就会出错.
以前是

    output: {
        publicPath: '/dist/',
    },

现在改为:

    output: {
        publicPath: '/productinfo/dist/',
    },

重新打包npm run build就好了.

附webpack.prod.config.js完整文件:

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const webpackBaseConfig = require('./webpack.base.config.js');
const fs = require('fs');

fs.open('./src/config/env.js', 'w', function(err, fd) {
    const buf = 'export default "production";';
    fs.write(fd, buf, 0, buf.length, 0, function(err, written, buffer) {});
});

module.exports = merge(webpackBaseConfig, {
    output: {
        publicPath: '/productinfo/dist/',
        filename: '[name].[hash].js',
        chunkFilename: '[name].[hash].chunk.js'
    },
    plugins: [
        new ExtractTextPlugin({
            filename: '[name].[hash].css',
            allChunks: true
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendors',
            filename: 'vendors.[hash].js'
        }),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new HtmlWebpackPlugin({
            filename: '../index_prod.html',
            template: './src/template/index.ejs',
            inject: false
        })
    ]
});

标签: none 阅读量: 1202

添加新评论