如何在Vue组件中引用全局函数?

Lin*_*inx 3 javascript function vue.js

我有一个 Vue 组件,它有一个“选择状态”下拉元素。我想添加一个 js 函数,用 50 个状态填充选项,而不必对它们进行硬编码。我还将在其他几个地方提供此下拉菜单,因此我希望从组件外部访问此函数。实现这一目标的最佳方法是什么?

<template>
    <div class="section" v-bind:class="sectionClass" data-mh="group3"> 
        <h3>{{sectionTitle}}</h3> 
        <div class="section-content display-area"> 
            <i class="icon icon-health img-left"></i> 
            <form> 
            <div class="row mt"> 
                <div class="col-xs-12 col-sm-8"> 
                  <div class="same-height-parent"> 
                      <div class="same-height"> 
                          <input type="text" class="form-control" placeholder="Enter Name"> 
                      </div>                                                 
                      <div class="same-height"> 
                          <select name="state" id="state" class="form-control" tabindex="9"> 
                              <option value="">- Select State -</option>
                          </select>                                                     
                      </div>                                                 
                  </div>                                             
                  <!-- same-height-parent -->                                             
                </div>                                         
                <div class="col-xs-12 col-sm-4"> 
                    <button type="submit" class="btn btn-success btn-block btn-fz20">Search</button>
                  </div>                                         
               </div>                                                                       
            </form>                                 
        </div>              
    </div>
</template>

<script>
    export default {
        name: 'nameSearch',
        data: function() {
            return {
                sectionTitle: 'Name Search'=
            }
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

Pab*_*noz 5

您可能想从其他文件导出该函数,这只是按照您想要的方式声明它的情况。

在其他一些文件中...

// utils.js
export function createOptions (someArg) {
  let options = [ ... ]
  return options
}
Run Code Online (Sandbox Code Playgroud)

在你的 .vue 文件中

<script>
  import { createOptions } from './utils'
  export default {
    ...
    data () {
      return {
        options: createOptions()
      }
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

您可能还想尝试 snovakovic 的建议来外部化下拉组件,无论什么都能给您带来更大的灵活性