Vue.js 在vue指令中使用全局函数

Vue.js 在vue指令中使用全局函数,vue.js,Vue.js,我试图在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>

我试图在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>

...
...
但是得到以下错误:

未捕获的TypeError:无法读取未定义的属性“isEmpty”


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

您只能在模板中访问当前Vue实例/组件的函数:

  • 资料
  • 道具
  • 方法
不能运行“第三方”代码

因此,您必须在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._
  }
}
然后它就可以访问了。如果
\uu
是有效的对象键,则为非正,因此如果需要,可以将其称为
lo
lodash


另外,假设comments是一个数组,使用
v-if='post.comments.length'
也不会有问题。Lo dash很棒,但如果你已经知道它是一个数组,那就不需要了。

作为vue.js的新手,这让我心碎!这是有意的:业务逻辑不属于模板。调试和重构是一场噩梦。当然,sweet-short-little-lodash函数不会造成太大的危害,但系统不能或不应该对sweet-little-lodash函数进行例外;)。也就是说,您可能可以将lodash作为一种实例方法注入Vue中:
Vue.prototype.\u=\ u
,这应该允许您在视图中以
\u
的形式访问它,但我不推荐这样做。