VueJS 组件

VueJS components

我想使用 VueJS 组件来清理我的脚本。因此,对于要加载到 Laravel 中的每个页面,我都有一个组件。到目前为止一切正常。但是我在将当前脚本逻辑传输到组件时遇到了问题。

这是导入要使用的组件的当前脚本设置:

main.js

import HomeView from './components/HomeView.vue';
import IncidentView from './components/IncidentView.vue';

window.app = new Vue({
   el: '.content',

   components: {
       HomeView, IncidentView
   },

   methods: {

       // Init GIS
      init: function() {

          // Initialize GIS Map
         initGISMap(this.$els.map);
      },
    }
(...)
}

对我来说关键是 window.app = new Vue... 部分。我使用 google 映射,因此当页面加载时它会搜索 app.init 方法。这是我在 blade 模板中加载的脚本的一部分:

<!DOCTYPE html>
<html>
<body class="hold-transition skin-blue sidebar-mini">
        <section class="content-header">
            <h1>
                @yield('page_title')
                <small>@yield('page_description')</small>
            </h1>
        </section>

        <!-- Main content -->
        <section class="content">

            @if (isset($vueView))
                <component is="{{ $vueView }}">
            @endif
                @yield('content')
            </component>

        </section>
        <!-- /.content -->
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places&callback=app.init" async defer></script>
</body>
</html>

各个页面(我在 Vue 中为每个模块创建的页面)如下所示:

@extends('app', ['vueView' => 'home-view'])
@section('page_title', 'title')
@section('page_description', 'title')

@section('content')
content
@endsection

通过定义 vueView 变量,使用了我在脚本中导入的正确模块。

目标是使用 HomeView 组件作为主要的 google 地图视图。以及在我的主题中单击相应的 link 时加载的不同页面的其他组件。最后,我不想在一个脚本中包含所有 VueJS 代码。因此模型。

当我传输当前 JS 文件的所有内容时,我收到一个错误,抱怨 app.init 不是一个函数。该组件如下所示:

<script>
export default {
   data: {
       // SEARCH
       addressComponents: '',
       autocompletePlace: '',
       autocompleteAddress: '',
(...)
}

如何以某种方式修改我的组件,使 app.init 负载仍然有效?

如果我没理解错的话,您有一个 Google 地图脚本,加载后会调用 window.app.init,对吗?

您的 Vue 组件是否有 init() 方法(none 如上所示)?如果有的话,它需要位于 app.methods.init() 请记住,对于 VueJS,标准可调用方法位于 methods 键下。

或者:您不提及 app.init 是否是 Vue 组件的一部分。如果不是,那么您的 app.init 函数将被覆盖,因为您正在将 window.app 重新定义为您的 vue 组件。

最后,如果您的 init 是 Vue 的一部分,您的 google maps fn 回调是否在加载 Vue 之前调用此 init() 并且因此不存在这样的方法(目前)?

也许您应该使用,或者至少研究一下执行此操作的程序包的代码。

例如,您可以在 Github 上检查 vue-google-maps : https://github.com/GuillaumeLeclerc/vue-google-maps/

它定义了大量与 Google 地图相关的组件。

有人已经提到 GuillaumeLeclerc/vue-google-maps 在 npm 上可用 vue-google-maps,但请注意该版本仅适用于 vue 1.x

如果您使用的是 v2,请查看这个很棒的 vue2 分支 xkjyeah/vue-google-maps - 它在 npm 上以 vue2-google-maps 的形式提供。

API 简单易懂,与 v1 版本相差无几,并且存储库比其上游版本活跃得多。

这真的让我的 vue 地图工作起来比自己滚动更轻松,这是我最初做的。

希望对你有所帮助