代码之家  ›  专栏  ›  技术社区  ›  nowox

如何在Vuejs 2中声明全局方法/对象?

  •  0
  • nowox  · 技术社区  · 7 年前

    我有一个 Vue 实例,其中我希望使所有组件都可以访问一些

    我写道:

    import mqtt from 'mqtt'
    
    new Vue({
      el: '#app',
      methods: {
        foo: function() {
          console.log("Hello Foo!");
        }
        mqtt: mqtt.connect('mqtt://server:8083')
      },
      render: h => h(App), 
      router
    });
    

    不幸的是,在我的组件中,我也无法访问 foo mqtt .

    <template>
    
    </template>
    <script>
    
    export default {
      data() {
        return {};
      },
      mounted() {
        this.foo(); // Doesn't work
        this.mqtt.on('connect', () => {}) // Doesn't work
      }
    }
    </script>
    

    发生了什么?

    1 回复  |  直到 7 年前
        1
  •  4
  •   mbuechmann    7 年前

    要分发纯函数(无副作用),可以使用mixin。

    const mixin = {
        methods:{
            foo() {
                console.log('foo')
            }
        }
    }
    

    new Vue({
        mixins: [mixin],
        // ...
    })
    

    该函数现在可以在每个组件中使用,就好像它定义在那里一样。

    您的mqtt连接完全是另一回事。您正在共享的结果 mqtt.connect Vuex 您可以跨多个组件共享状态并定义突变。

    在中定义存储 src/store/index.js :

    const store = new Vuex.Store({
      state: {
        connected: false,
        result: null
      },
      mutations: {
        setMqtt (state, mqttResult) {
          state.connected = true
          state.result = mqttResult
        }
      }
    })
    

    import store from './store'
    
    new Vue({
      el: '#app',
      mixins: [mixin],
      store,
      // ....
    })
    

    现在,您可以通过以下方式在每个组件中访问此存储:

    this.$store.state.connected
    this.$store.state.result
    

    只能在中定义的函数中进行访问 computed . 一旦状态发生任何变化,将再次计算computed中定义的所有函数。

    现在,您可以获取主文件中的数据并提交结果:

    mqtt.connect('mqtt://server:8083').on('connect', (someData) => {
        store.commit('setMqtt', someData)
    })
    

    https://vuejs.org/v2/guide/mixins.html

    https://vuex.vuejs.org/