【问题标题】:Pass data from VueJS Plugin to VueJS Component将数据从 VueJS 插件传递到 VueJS 组件
【发布时间】:2017-02-16 22:56:24
【问题描述】:

我正在为 VueJS 创建一个加载栏插件,我想使用该插件控制 VueJS 组件(插件的一部分)的数据。

所以,最后我想做以下事情:

在 main.js 中包含插件

import VueLoadingBar from 'path-to-plugin';

Vue.use(VueLoadingBar);

在 App.vue 中包含插件组件

<template>
  <div id="app">
    <vue-loading-bar><vue-loading-bar>
  </div>
</template>

在各种组件中,我想使用 this.$loadingBar.start() 为进度条(例如 Youtube)设置动画。


我的插件包含一个插件 JavaScript 文件...

import LoadingBar from './LoadingBar.vue';

const vueLoadingBar = {
  install () { 
    const loadingBarModule = {
      start () {
        // Start animating by setting the computed `progress` variable in the component, for simple
        // demonstration with setInterval
        setInterval(() => { 
          // How do I set `progress` that updates the component. Or is there an even better way to solve this?
        }, 500);
      }
    }

    Vue.component('vue-loading-bar', LoadingBar);

    Vue.prototype.$loadingBar = loadingBarModule;
  }
}

export default vueLoadingBar;

...和一个.vue 文件

<template>
  <div class="c-loading-bar" :style="style"></div>
</template>

<script>
  export default {
    computed: {
      style () {
        return {
          transform: `translateX(${this.progress}%)`,
        }
      },
      progress() {
        return 0;
      }
      /* other computed data */
    }
  }
</script>

<style>
  .c-loading-bar {
    position: fixed;
    top: 0;
    z-index: 20;
    height: 5px;
    background: red;
  }
</style>

从插件中“控制”LoadingBar 组件的最佳方式是什么(例如 this.$loadingBar.start())?

【问题讨论】:

  • 为什么不做一个简单的loader组件,做一个progress prop来控制呢?如果您真的想坚持使用插件,您可以接收进度道具并触发一些已完成/开始的事件
  • @Afik​​Deri 我只会在我的应用程序中包含一次组件,但我想在我的应用程序的各个部分(例如 AJAX、路由,在某些其他情况下)控制(启动加载动画)。因为我不想在每次加载某些东西时都包含一个新组件,所以我需要某种全局“函数”(这就是为什么我认为我需要this.$loadingBar)。您将如何在插件中接收进度和触发事件的道具?

标签: javascript vuejs2


【解决方案1】:

对于任何感兴趣的人:最后,我给了我的组件一个数据name

export default {
  data () {
    return {
      name: 'UNIQUE_NAME',
    };
  }
}

并将以下代码添加到我的插件install 函数中

Vue.mixin({
  created() {
    if (this.name === 'UNIQUE_NAME') {
      console.log('You can now access the component with', this);
    }
  },
});

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 2019-03-22
    • 2020-11-08
    • 1970-01-01
    • 2020-12-29
    • 2020-12-29
    • 2018-09-12
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多