【问题标题】:Using Vue with Django: How to separate publicPath from static file prefix在 Django 中使用 Vue:如何将 publicPath 与静态文件前缀分开
【发布时间】:2021-05-02 21:46:31
【问题描述】:

我正在尝试将我现有且庞大的 Django 项目(该项目目前在前端的各个页面中使用 CDN 中的 Vue)通过 NPM 转换为 SPA,其中后端和前端现在是分开的(Django 处理一些 URL 路由除外并最初加载 Vue)。

我遇到了静态文件和 URL 路由问题。在vue.config.js 中,我最初被建议设置如下值:

const pages = {
  index: "src/main.js"
};
module.exports = {
  runtimeCompiler: true,
  publicPath: "/static/vue/",
  outputDir: "./dist/static/vue/",
  indexPath: "../../templates/vue_index.html",
  pages: pages
};

这样当结合 Django 查找静态文件的方式时:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'frontend/dist/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontend/dist/static')]
STATIC_URL = '/static/'

页面将能够加载。

不幸的是,如果我尝试加载页面,而不是在网站根 / 加载,它会在 /static/vue/ 加载(即 localhost:8000/static/vue/)。如果我尝试直接访问 localhost:8000,它会立即重定向到 localhost:8000/static/vue/,我想这是 vue-router 所做的。

Django 能够很好地找到 Vue 入口点模板,但它似乎需要 publicPath: "/static/vue/" 才能正确地为 .js 和 .css 文件添加 Django 在静态 URL 上所需的 /static/ 前缀(即使我可以将/static/ 更改为/ 提供的所有静态文件,我更喜欢开箱即用的/static/ 前缀)。

如果我将 publicPath: "/static/vue/" 更改为 publicPath: "/"publicPath: "./",模板文件仍然可以正确提供,但我现在丢失了 .js 和 .css 文件所需的 /static/vue/ 前缀,所以他们 404。

我如何能够告诉 Vue(或者更具体地说是 vue-cli)在 / 处提供我的应用程序的根页面,但在初始模板中引用的所有静态文件前面加上 /static/ 或 @987654337 @?

【问题讨论】:

    标签: django vue.js vue-cli


    【解决方案1】:

    终于找到了答案。对于 Vue 3,在 vue-router 中设置基本 URL:

    const router = createRouter({
      history: createWebHistory("/"),
      routes
    });
    

    【讨论】:

    • 谢谢,它帮助了我。如果你有像 my-app 这样的子路径,那么我们可以使用 createWebHistory("/my-app/")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 2020-03-21
    • 2019-03-05
    • 2012-03-25
    • 2011-12-08
    • 1970-01-01
    相关资源
    最近更新 更多