在 vue 指令中使用全局函数

Use global functions in vue directives

我正尝试在 vue 指令中使用 lodash 方法 (_.isEmpty),如下所示:

<div class="post" v-for="post in posts"></div>
    ...
    <div class="comments" v-if="! _.isEmpty(post.comments)">
      <div class="comment" v-for="comment in post.comments"></div>
    </div>
    ...
</div>

但出现以下错误:

Uncaught TypeError: Cannot read property 'isEmpty' of undefined

vue 似乎在当前范围内寻找 _.isEmpty 方法。在这种情况下我应该如何调用全局函数?

您只能在模板中访问当前 Vue instance/component 的功能:

  • 数据
  • 道具
  • 方法

没有"third-party"代码可以是运行.

因此,您必须在 Vue 组件中创建一个方法来代理 lodash 方法:

methods: {
  isEmpty: function (arr) { return _.isEmpty(arr)}
}

并在模板中改用此方法:

<div class="comments" v-if="! isEmpty(post.comments)">

为什么不直接将 _ 添加到您的 Vue 组件中:

data(){
  return {
    _:require('lodash')  //or however you include it. maybe just window._
  }
}

然后就可以访问了。如果 _ 是一个有效的对象键,则不是肯定的,因此如果需要,可以将其称为 lolodash

另外,假设comments是一个数组,使用v-if='post.comments.length'也没有问题。 Lo-dash 很棒,但如果您已经知道它是一个数组,则没有必要。