【问题标题】:How to use VUE router with native HTML elements as components?如何使用带有原生 HTML 元素的 VUE 路由器作为组件?
【发布时间】:2021-02-03 14:11:03
【问题描述】:

我处于这种情况:

  • 旧项目,npm/vue 编译器不可用
  • 在香草 JS 风味中使用 vue
  • 使用路由器,需要组件
  • 不想使用臭气熏天的注入字符串,这对代码的可读性非常不利

如何使用 html 片段作为 vanilla JS vue 的组件?

【问题讨论】:

  • 也许标题可能是“如何将 Vue Router 与 Vanilla JS 一起使用”,因为使用 vanilla JS + HTML 模板是文档中discussed 的第一件事
  • 已更正,但关键是文档仅声明使用带有注入字符串模板的路由器,我想避免这种方法,因为原生 html 模板更好(就像编译的 vue 一样)

标签: vue.js vue-router


【解决方案1】:

我找到了一个完全没有文档的解决方案,用于使用原生 HTML 制作 vanilla JS 组件:

1 纯 HTML(没有臭味注入的字符串):

   <div id="components" style="display:none"><!--hide component code-->
        <div id="component-category-index"><!--component 1 source code-->
            CATEGORY INDEX COMPONENT
        </div>
        <div id="component-article-show"><!--component 2 source code-->
            ARTICLE SHOW COMPONENT
        </div>
    </div>

2 vanilla JS Vue 初始化:

const vue=new Vue({
    el: '#vue-app',
....your vue blabla.....
    router:new VueRouter({
        routes :[
            { path: '/article', component: { template: document.getElementById('component-article-show').outerHTML } },
            { path: '/categories', component: { template: document.getElementById('component-category-index').outerHTML } }
        ]
    })
})

优点:

  1. 使用具有完整组件功能的 vanilla JS vue
  2. 保持 vue "style-component-logic" 分开但在同一个文件中,没有 很难打破这种干净简单的模式

缺点:

页面的所有 HTML 必须在同一个文件中,因此此解决方案适用于较小的 SPA 或带有 VUE 的单个页面。

【讨论】:

    猜你喜欢
    • 2022-06-15
    • 2021-02-08
    • 2021-12-05
    • 2019-04-10
    • 2016-09-08
    • 2019-11-03
    • 2019-06-26
    • 2018-10-31
    • 2021-03-08
    相关资源
    最近更新 更多