heyujie
2021-05-20 6ebdefb4a5b2be82a8c452c0bb4624f3d85a17b7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import Observer from './Observer'
import Emitter from './Emitter'
 
export default {
 
    install(Vue, connection, options) {
 
        if (!connection) throw new Error("[Vue-Mqtt] cannot locate connection");
 
        let observer = new Observer(connection, options);
 
        Vue.prototype.$mqtt = observer.Mqtt;
 
        Vue.mixin({
            created() {
                let mqtt = this.$options['mqtt'];
 
                this.$options.mqtt = new Proxy({}, {
                    set: (target, key, value) => {
                        Emitter.addListener(key, value, this);
                        target[key] = value;
                        return true;
                    },
                    deleteProperty: (target, key) => {
                        Emitter.removeListener(key, this.$options.mqtt[key], this);
                        delete target.key;
                        return true;
                    }
                });
 
                if (mqtt) {
                    Object.keys(mqtt).forEach((key) => {
                        this.$options.mqtt[key] = mqtt[key];
                    });
                }
            },
            beforeDestroy() {
                let mqtt = this.$options['mqtt'];
 
                if (mqtt) {
                    Object.keys(mqtt).forEach((key) => {
                        delete this.$options.mqtt[key];
                    });
                }
            }
        })
 
    }
 
}