javascript - 如何在 Laravel 5.3 的 Vue.js 2.0 组件中使用外部 html 模板

标签 javascript php laravel laravel-5.3 vuejs2

我正在使用默认的 Laravel 5.3 安装程序——全新安装,具有 Vue.js 2.0 的默认配置。

使用 Laravel 5.1 和 Vue.js 1.x,我可以轻松定义组件,并使用 browserify 进行编译。

Vue.component('test-component', require('./test-component');  

/*  test-component.js */
export default{
    template:require('./test-component.template.html')
}

/* test-component.template.html  */
<div class="test-component">
    <h1> Test Component <h1>
</div>  

但是,对于 Vue 2,默认是 webpack(尽管 browserify 也可用,但无法使其工作,而且 webpack 似乎更好).但是我无法使配置正常工作。

我尝试了各种配置,最后在我的 gulp.js 文件中有了它

const elixir = require('laravel-elixir');
require('laravel-elixir-vue-2'); 

var config = {

    module:{
        loaders:[
            {
                test: /\.html$/,
                loader: 'vue-loader'
            }
        ]
    }
};
elixir(mix => {
    mix.sass('app.scss')
       .webpack('app.js',null, null, config);
});  

现在我在编译 gulp webpack 时没有收到任何错误,但是当我尝试在浏览器中查看页面时,它不显示组件并且在控制台中有错误/警告

vue.js?3de6:513[Vue warn]: invalid template option:[object Object] 
(found in component <test>)

vue.js?3de6:4085Uncaught TypeError: Cannot read property 'child' of null(…)  

我的app.js主入口文件(Laravel默认提供)

require('./bootstrap');

Vue.component('test-component', require('./components/test-component'));

const app = new Vue({
    //el: '#app',
}).$mount('#app');  

我错过了什么?任何指针将不胜感激。

最佳答案

  1. 您必须使用 html-loader 而不是 vue-loader

    npm install html-loader --save-dev
    
  2. 您的gulpfile.js(需要更改loader):

    const config = {
      module: {
        loaders:[{
          test: /\.html$/,
          loader: 'html'
        }]
      }
    };
    
    elixir((mix) => {
      mix.sass('app.scss')
        .webpack('app.js', null, null, config);
    });
    
  3. 您的 test-component.js(无需更改,一切顺利):

    export default {
      template: require('./test-component.template.html')
    }
    
  4. 您的 test-component-template.html:(无需更改,一切顺利)

    <div class="test-component">
      <h1>Test Component Goes Here</h1>
    </div>
    

重要

  1. 定义组件的方法如下:

    • 使用默认值

      Vue.component('test-component', require('./test-component').default);
      
    • 或者,简单地使用 ES2015 import

      import TestComponent from './test-component';
      
      Vue.component('test-component', TestComponent);
      

关于javascript - 如何在 Laravel 5.3 的 Vue.js 2.0 组件中使用外部 html 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41115436/

相关文章:

php - Laravel - Twig View 中的 print_r

javascript - 刷新同一页面而不重新加载 - Reactjs

javascript - npm --> 错误 : Cannot find module 'readable-stream'

PHP:浏览数据

php - 使用 php 更改 4 个结果的背景颜色

php - 表单提交后,滚动到表单

php - Laravel 5 多个下载文件

javascript - Chrome 操作系统(隐身)和 Linux Chrome 网络字体显示问题

javascript - vue.js 表格中的条件渲染

php - 当 curl 尝试解析主机时,如何更改 php curl 超时 (curl err_no 6)