【问题标题】:How can I load a specific component from an HTML template in VueJS?如何从 VueJS 中的 HTML 模板加载特定组件?
【发布时间】:2021-04-02 11:31:34
【问题描述】:

我使用 webpack 加载器将 VueJS 添加到我的 Django 项目中。 Vue 可以工作,但我对它很陌生,所以我很难理解它的结构。

我有以下模板:

django_template.html:这是我加载 Vue 应用程序的地方

{% load render_bundle from webpack_loader %}

{% block content %}
    
<div id="app">
    <app></app>
</div>
                      
{% render_bundle 'chunk-vendors' %}
{% render_bundle 'chart' %}

{% endblock %}

现在我的 Vue 应用程序有两个基本组件,一个是 testComponent1.vue

<template><h1>This is the test component one</h1></template>

另一个是testComponent2.vue

<template><h1>This is the test component two</h1></template>

然后我有 App.vue

<template>
  <div>
    <testComponent1></testComponent1>
    <testComponent2></testComponent2>
  </div>
</template>

<script>
import testComponent1 from "./components/testComponent1";
import testComponent2 from "./components/testComponent2";

export default {
  name: "App",
  components: {
    'testComponent1': testComponent1,
    'testComponent2': testComponent2,
  },
};

</script>

最后是 ma​​in.js

import Vue from "vue";
import App from "./App.vue";
import axios from 'axios'

import Vuetify from "vuetify";
import "vuetify/dist/vuetify.min.css";

Vue.use(Vuetify);

Vue.config.productionTip = false;

new Vue({
  render: h => h(App),
  vuetify: new Vuetify()
}).$mount("#app");

现在我的问题是:

如何只调用特定组件而不是全部?我提供的代码将加载 vue 应用程序的所有组件,但由于我在 Django 中使用 Vue,因此在某个 HTML 页面上我需要一些组件,在另一个页面上我需要另一个组件。任何形式的建议表示赞赏!

【问题讨论】:

  • Django 如何通知你的 VueJS 应用加载哪个组件?
  • Vue 并不适合渲染经典的 Django 页面/路由。 Vue是一个框架来构建一个single page app; Django 为整个 Vue 应用程序提供一次服务,然后通常只与在浏览器中运行的 Vue 应用程序交换纯数据。可以使用 Vue 的 router package 模拟 SEO URL,但通常,是否显示组件是使用条件渲染实现的,其中应用程序的(不断变化的)状态决定了哪些组件作为 DOM 的一部分出现,哪些那些被删除了。
  • 除非你对经典的服务器端渲染和 SPA 渲染有很好的理解,否则我建议坚持使用 Django 模板或使用 Vue。
  • 感谢您的回答!我不同意 Vue 仅适用于 SPA,我很确定他们明确表示 Vue 也可用于 SSR 应用程序或渐进式 Web 应用程序。这就是 webpack-loader 的用途

标签: javascript vue.js


【解决方案1】:

有数以千计的选项可供您选择。 如果您只想禁用它们,最简单的方法就是使用if/else 声明:

https://vuejs.org/v2/guide/conditional.html

`Vue 太棒了!

哦不?`

或者你可以使用动态组件:

https://vuejs.org/v2/guide/components-dynamic-async.html

<component v-bind:is="currentComponent"></component>
export default {
  name: "App",
  data: () => { currentComponent: 'testComponent1' }
  components: {
    'testComponent1': testComponent1,
    'testComponent2': testComponent2,
  },
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-16
    • 2020-07-24
    • 2018-12-24
    • 1970-01-01
    • 2023-02-16
    • 2014-11-23
    • 2019-02-24
    • 2022-01-23
    相关资源
    最近更新 更多