首页 > 解决方案 > Vue js中的Mixin(在组件之间切换时无法获取组件中的更新值)

问题描述

我在vue js中使用全局mixin,但问题是当我在组件之间切换而我从方法返回值时我的组件没有获得更新的值(当我切换状态(离线/在线)时我能够得到它在同一再次组件)。我想在不刷新浏览器的情况下根据网络检测更新“checkOnline”的值,这可以正常工作,但是如果我导航到其他选项卡并且他们断开网络并返回上一个选项卡,则“checkOnline”的状态不会更新。

x.js

import {bus} from '../main';
export default {
  data() {
    return {
      checkOnline: navigator.onLine || false
    }
  },
  created() {
    bus.$on('detected-condition', this.disableButton)
  },
  watch: {
    checkOnline: function (val) {
        if (navigator.onLine) {
          return true
        } else {
          return false
        }
    }
  },
  methods: {
    disableButton($event) {
      if ($event) {
        this.checkOnline = false
      } else {
        this.checkOnline = true
      }
    }
  }
}

一个.vue

<v-flex xs12 class="text-xs-center">
       <v-btn fab dark small :color="checkOnline ? 'grey' : 'primary'" class="mx-0 mb-0 elevation-4" :class="{disabled: checkOnline}" >
         <v-icon>file_download</v-icon>
       </v-btn>
     </v-flex>

b.vue

import {bus} from '../main';
  const EVENTS = ['online', 'offline', 'load'];

  export default {
    props: {
      onlineClass: {
        type: String,
        required: false
      },
      offlineClass: {
        type: String,
        required: false
      }
    },
    data () {
      return {
        isOnline: navigator.onLine,
      }
    },
    mounted() {
      EVENTS.forEach(event => window.addEventListener(event, this.updateOnlineStatus));
    },
    beforeDestroy() {
      EVENTS.forEach(event => window.removeEventListener(event, this.updateOnlineStatus));
    },
    computed: {

    },
    methods: {
      updateOnlineStatus() {
        this.isOnline = navigator.onLine || false;
       bus.$emit('detected-condition', this.isOnline);
      }
    }
  };

标签: javascriptvue.js

解决方案


推荐阅读