Skip to content

[vue] vue在组件中引入插件的方法有哪些? #271

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

[vue] vue在组件中引入插件的方法有哪些?

Activity

wenyejie

wenyejie commented on Jun 17, 2019

@wenyejie

不是很明白题主的意思, 先mark一下

forever-z-133

forever-z-133 commented on Jun 18, 2019

@forever-z-133

现在随着组件库越来越多,插件好像就用得少了。

canwdev

canwdev commented on Feb 22, 2020

@canwdev

插件

插件通常用来为 Vue 添加全局功能。插件的功能范围没有严格的限制——一般有下面几种:

  1. 添加全局方法或者属性。如: vue-custom-element
  2. 添加全局资源:指令/过滤器/过渡等。如 vue-touch
  3. 通过全局混入来添加一些组件选项。如 vue-router
  4. 添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
  5. 一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router

示例:安装 ElementUI

  1. 安装:yarn add element-ui

  2. 引入,在 main.js 中写入以下内容:

    import Vue from 'vue'
    import App from './App.vue'
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    
    Vue.config.productionTip = false
    Vue.use(ElementUI);
    new Vue({
      render: h => h(App),
    }).$mount('#app')
  3. 在组件中使用:

    <template>
      <div>
        <Button>Button</Button>
      </div>
    </template>
    
    <script>
    import { Button } from 'element-ui';
    
    export default {
      components: {
        Button
      }
    };
    </script>
  4. 更多配置参考 官方文档

jim888666

jim888666 commented on May 14, 2020

@jim888666

Vue.use(xx)
Vue.prototype.xxx = xxx
是这样吗?
请大佬们指证

radio-qq

radio-qq commented on Jan 4, 2021

@radio-qq

npm安装,在main.js里import,然后Vue.use(xx)后便可全局使用,
有些特殊的需要做配置,如less、scss插件,还要在webpack下配置好对应的loader

radio-qq

radio-qq commented on Jan 4, 2021

@radio-qq

Vue.use(xx)
Vue.prototype.xxx = xxx
是这样吗?
请大佬们指证

Vue.use(xx)=》注册插件
Vue.prototype.xxx = xxx=》绑定方法
不是同一个东西,插件包含多个方法、多个属性.....一大堆,而Vue.prototype.xxx = xxx只是引入插件里的一小个方法而已

Cai-zhiji

Cai-zhiji commented on Jul 7, 2023

@Cai-zhiji

全局引入:

将插件在应用的入口文件中全局引入,使其在所有组件中可用。在main.js或类似的入口文件中使用Vue.use()方法引入插件。

// main.js
import Vue from 'vue';
import MyPlugin from 'my-plugin';

Vue.use(MyPlugin);

引入后,插件中的组件、指令、过滤器等将在整个应用范围内可用。

局部引入:

在需要使用插件的组件中进行局部引入。可以在组件的<script>块中使用import语句引入插件,然后在components选项或directives选项中使用。

<template>
  <div>
    <my-component></my-component>
  </div>
</template>

<script>
import MyComponent from 'my-component';

export default {
  components: {
    MyComponent
  }
};
</script>

使用局部引入时,插件中的组件、指令等仅在该组件及其子组件中可用。

插件选项引入:

一些插件允许通过传递选项来进行引入和配置。可以在组件的选项中通过plugins属性来引入插件并进行配置。

export default {
  plugins: [
    MyPlugin({
      // 插件配置选项
    })
  ]
};

这种方式允许对插件进行更细粒度的配置。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @wenyejie@haizhilin2013@canwdev@forever-z-133@jim888666

        Issue actions

          [vue] vue在组件中引入插件的方法有哪些? · Issue #271 · haizlin/fe-interview