Javascript 在所有 vue 组件模板中使用 lodash

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37694243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:39:14  来源:igfitidea点击:

Using lodash in all of vue component template

javascriptlodashvue.jsvue-component

提问by antoniputra

Can I use lodash _in all of my vue component?

我可以_在我的所有 vue 组件中使用 lodash吗?

for example:

例如:

I have components organized like below:

我有如下组织的组件:

App.vue> Parent.vue> Child.vue

App.vue> Parent.vue>Child.vue

I would like all of my component to access _lodash without defined in every component vm data

我希望我的所有组件都可以访问_lodash 而不在每个组件 vm 中定义data

===

===

I am also trying using Mixins. it works. but the result not expected like this _().isEmpty()instead of _.isEmpty()

我也在尝试使用Mixins。有用。但结果不是这样的,_().isEmpty()而不是_.isEmpty()

回答by anthonygore

Some of the current answers may work in your scenario, but they have downsides:

当前的一些答案可能适用于您的场景,但它们有缺点:

  • Adding to the windowobject means your Vue project can't be server rendered, because servers don't have access to the windowobject.
  • Importing in every file works fine, but it can be a pain if you have to remember to do it in every file.
  • 添加到window对象意味着您的 Vue 项目不能被服务器渲染,因为服务器无权访问该window对象。
  • 在每个文件中导入都可以正常工作,但是如果您必须记住在每个文件中都进行导入可能会很痛苦。

An alternative approach is to add your library to the Vue prototype. All components inherit from this so they will now all be able to access your library from the thiskeyword.

另一种方法是将您的库添加到 Vue 原型中。所有组件都继承自此,因此它们现在都可以从this关键字访问您的库。

import _ from 'lodash';    
Object.defineProperty(Vue.prototype, '$_', { value: _ });

Now lodash is available as an instance method for all components. In a .vue file you can do this without importing anything:

现在 lodash 可用作所有组件的实例方法。在 .vue 文件中,您无需导入任何内容即可执行此操作:

export default {
  created() {
    console.log(this.$_.isEmpty(null));
  }
}

The advantage of using Object.definePropertyrather than a normal property assignment is that you can define a descriptor which allows you to make the property read-only, which it will be by default. This stops consuming components from overwriting it.

使用Object.defineProperty而不是普通属性分配的优点是您可以定义一个描述符,该描述符允许您将属性设为只读,默认情况下它将是只读的。这会阻止消耗组件覆盖它。

This is more thoroughly explained in this blog post(which I wrote).

这在这篇博文(我写的)中有更详尽的解释。

Note: The downside to this approach is that you get the entire Lodash library, even if you only need one or two functions. If that's a problem, best to use import { reduce, whatever } from "lodash";at the top of the file requiring it.

注意:这种方法的缺点是你会得到整个 Lodash 库,即使你只需要一两个函数。如果这是一个问题,最好import { reduce, whatever } from "lodash";在需要它的文件的顶部使用。

回答by Pantelis Peslis

You could import the lodashinto each component:

您可以将 导入lodash到每个组件中:

<script>
  import _ from 'lodash'

  export default {
    methods: {
      test (value) {
        return _.isEmpty(value)
      }
    }
  }
</script>

回答by antongorodezkiy

For inline templates separated from the js module code it should work with:

对于与 js 模块代码分离的内联模板,它应该使用:

  Vue.component('some-tag', {
    computed: {
      _() {
        return _;
      }
    }
  });

And then you can use it in template in "native"way - _.isEmpty(value).

然后您可以以“本机”方式在模板中使用它- _.isEmpty(value)

回答by butaminas

import _ from 'lodash'
Vue.prototype._ = _

Insert these lines in your main.js file and it will work all over your app.

在您的 main.js 文件中插入这些行,它将在您的应用程序中运行。

回答by Brandon Ferens

You could import lodashglobally like this

你可以lodash像这样全局导入

window._ = require('lodash');

Once that has been imported, you will have access to _from anywhere.

一旦导入,您就可以_从任何地方访问。

回答by newms87

A simple approach that worked for me:

一种对我有用的简单方法:

Vue.set(Vue.prototype, '_', _);

Vue.set(Vue.prototype, '_', _);

This should allow you to use _ in all component templates and vue instances.

这应该允许您在所有组件模板和 vue 实例中使用 _。

回答by Hotbrains

You can use plugin/mixin like this.

你可以像这样使用插件/混合。

import _ from 'lodash';
exports default {
    install : function(Vue, options){
        Vue.mixin({
            computed : {
                "_" : function(){
                    return _;
                }
            }
        });
    }
}

回答by user8888

Bit late to the party but through my research of finding a way to import lodash and other libraries into all my .vue files, I encountered the webpack ProvidePlugin, which achieves everything the OP requested with almost no fuss. To implement this solution, following this fantastic tutorial.

有点迟到了,但通过我找到一种方法,导入lodash和其他图书馆为我所有的.vue文件的研究,我遇到的WebPack ProvidePlugin,达到了OP请求几乎没有什么大惊小怪的一切。要实施此解决方案,请遵循这个精彩的教程

I would note that in the tutorial, he left import "jquery"in his app.js file, which is not required. The plugin with import it automatically.

我会注意到,在教程中,他留import "jquery"在了他的 app.js 文件中,这不是必需的。插件会自动导入。

回答by Ewing

Check out vue-lodash!! It's a new wrapper for using lodash in vue. You can call it using

查看 vue-lodash !!它是在 vue 中使用 lodash 的新包装器。你可以调用它使用

Vue._.random(20) // for getting random number between 20

this._.random(20) //or other method you want to use

Vue._.random(20) // 用于获取 20 之间的随机数

this._.random(20) //或者你想使用的其他方法

in any of the component file :)

在任何组件文件中:)

回答by Leonardo Raele

You can also create a base component and make all of your components extend it.

您还可以创建一个基础组件并使您的所有组件对其进行扩展。

// base-component
import _ from 'lodash';

export default Vue.extend({
  computed: {
    _() {
      return _;
    },
  },
});
// my-component
import BaseComponent from 'path/to/base-vue';

export default BaseComponent.extend({
  template: '<p>Lodash is available: {{!!_}}</p>'
  methods: {
    doSomehting() {
      // `this._` should be available
    },
  },
});

The proof this approach is it's not intrusive, so no possible conflict with Vue in the future. Also, you can add even more things to the BaseComponent, like other libraries and external services, and they will be available to all other components.

这种方法的是它不是侵入,所以在未来的Vue没有可能发生的冲突。此外,您可以向 BaseComponent 添加更多内容,例如其他库和外部服务,它们将可用于所有其他组件。

The conis it's more verbose and you have to remember to inherit from the base component.

CON是它的更详细的,你必须从基础构件记得继承。