存储有数据时如何调用函数

How to call a function when store has data

我必须创建一个视频播放器对象,但我需要在创建视频播放器之前存在流对象

this.stream 由 vuex 数据存储填充。但我发现 mounted()created() 方法不等待存储数据出现。

这是 Player.vue 组件:

import Clappr from 'clappr';
import { mapActions, mapGetters } from 'vuex';
import * as types from '../store/types';

export default {
  name: 'streams',
  data() {
    return {
      player: null
    };
  },

  computed: {
    ...mapGetters({
      stream: types.STREAMS_RESULTS_STREAM
    }),

    stream() {
      return this.$store.stream;
    }
  },

  methods: {
    ...mapActions({
      getStream: types.STREAMS_GET_STREAM
    })
  },

  mounted() {
    this.getStream.call(this, {
      category: this.$route.params.category,
      slug: this.$route.params.slug
    })
      .then(() => {
        this.player = new Clappr.Player({
          source: this.stream.url,
          parentId: '#player',
          poster: this.stream.poster,
          autoPlay: true,
          persistConfig: false,
          mediacontrol: {
            seekbar: '#0888A0',
            buttons: '#C4D1DD'
          }
        });
      });
  }
};

有没有办法等待this.stream出现?

您可以订阅突变事件,例如,如果您的商店中有一个名为 setStream 的突变,您应该订阅此突变。下面是如何在挂载方法中订阅的代码片段。

mounted: function () {
  this.$store.subscribe((mutation) => {
    if (mutation.type === 'setStream') {
      // Your player implementation should be here.
    }
  })
}