在没有 Webpack/Bundlers 的 PHP 中镜像 Vue 组件

我正在尝试在我的公司使用 Vue。目前我们没有使用任何像 Webpack 这样的 Javascript 构建工具。这意味着没有 Babel,(Babel-Standalone 也不是一个选项)。No Babel 意味着没有 Template Literals (``),这使得在纯 Javascript 文件中定义组件变得很痛苦(Internet Explorer 不支持 Template Literals,并且要在干净的多行代码中在 Javascript 中定义模板,您需要 Template Literals,我们需要 IE支持)。我的团队已经同意在不久的将来转向 Laravel 和 Vue,但我们正在通过服务器迁移和代码更新,然后才能正确使用 Vue。

所以我想我会尽量模仿 .vue 布局。首先,我在 PHP 或 HTML 文件中创建组件,在 X-Template 中定义模板以及 Vue 组件实例化和样式。在我的 PHP 控制器/类/等中。我需要该文件,它在 DOM 中呈现。这个解决方案有效,但我有几个问题。

  • 有没有什么不可预见的问题?

  • 有没有办法将这些 .php/HTML 文件的内容作为源包含而不是在 DOM 中呈现?

例子

// MyComponent.php or MyComponent.html


<script type="text/x-template" id="my-component-template">

    // component template definition

</script>


<script>

    Vue.component('myComponent', {

        template: '#my-component-template',

        // component vue data/methods/etc

    });

</script>


<style>

    // component styling

</style>

-


// MyPhpClass.php


public function includeComponents() {

    include('path/to/MyComponent.php');

}


翻过高山走不出你
浏览 163回答 2
2回答

吃鸡游戏

您采用的方法可以正常工作,但当然缺乏在 webpack 中处理 *.vue 文件时提供的简单性和功能性。我最近在一个个人项目中遇到了一个类似的用例,为此我在 PHP 中通过一些作曲家依赖项解决了它。我正在链接到GitHub 上的存储库。包含的类公开了一个render函数,该函数接受文件路径数组到您希望解析的许多 *.vue 文件。它将处理它们并将它们转换为批处理<script>和<style>标签。生成的脚本代码应符合 IE 9+。如果您想将代码通过管道传输到外部源文件以通过 HTML 加载,还有一些函数可以直接检索getScripts代码。getStyles您的方法之间的主要区别集中在功能模板和范围样式的处理上,这两种方法都在此解决方案中得到支持。还有一些额外的开销在我的情况下是可以接受的,但可以通过使用上述两种额外的方法并缓存结果来减轻。一个基本的用例可能是这样的:<?php&nbsp; &nbsp; $vueFiles = glob(__DIR__ . '/vue-components/*.vue');&nbsp; &nbsp; // Output scripts before browser gets to custom elements&nbsp; &nbsp; // because IE crashes if it's not registered first&nbsp; &nbsp; VueLoader::render($vueFiles, '#vue-app');?><div id="vue-app">&nbsp; &nbsp; <my-custom-component></my-custom-component></div>

隔江千里

我也遇到过这个问题,得出的结论是:Vue 没有为我们提供一种packing在 html 中包含多个组件的便捷方式。如果是这样,我们的 php 问题就不会存在,我们可以连接一些 vue 文件并继续我们的业务。如果你可以这样写:<template component="my-component">&nbsp; <div>&nbsp; &nbsp; <!-- template html here -->&nbsp; </div>&nbsp; <style scoped>&nbsp; &nbsp; <!-- style here -->&nbsp; </style>&nbsp; <script>&nbsp; &nbsp; // vue component definition here.&nbsp; &nbsp; export default {&nbsp; &nbsp; &nbsp; data(){&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; variable: 'my value'&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; </script></template>现在整个组件都包含在一个模板元素中。这些模板元素可以在客户端上提取和重建。为了避免你不得不重新发明这个轮子,你可以使用vue-blocks。它是 Vue/VueRouter 之上的一个层,它从可用的 html 中提取这些组件并注册它们。
打开App,查看更多内容
随时随地看视频慕课网APP