vue.jsvuejs3vue-devtoolsvue-options-api

vue3 devtools: How to access component methods using Options API?


In devtools with Vue2 I can access my components methods by selecting a component in vue devtools and then type $vm0.myMethod() in the console.

export default {
  // ...
  methods: {
    myMethod() {
      console.log('hello');
    },
  }
  // ...
}

Now I'm using Vue3 with options API. How can I still access my component methods?


Solution

  • Given that the methods are specified in methods for options API: {

    <script>
    export default {
      expose: ['publicMethod'],
      methods: {
        privateMethod() {...}
        publicMethod() {...}
      },
    }
    </script>
    

    For composition API, it's presumed that component methods are returned from setup function:

    <script>
    export default {
      setup(props, ctx) {
        function justLocalFunction() {...}
        function privateMethod() {...}
        function publicMethod() {...}
    
        ctx.expose({ publicMethod })
    
        return { privateMethod, publicMethod };
      }
    }
    </script>
    

    This is implicitly done with script setup syntax:

    <script setup>
    export default {
      setup(props, ctx) {
        {
          // Block scope isn't magically transformed
          function justLocalFunction() {...}
        }
    
        function privateMethod() {...}
        function publicMethod() {...}
    
        defineExpose({ publicMethod })
      }
    }
    </script>
    

    Here only publicMethod is available on component ref. While privateMethod and publicMethod are exposed on internal component instance, which can be accessed as getCurrentInstance().proxy.privateMethod, etc inside setup block, and as devtools $vm.proxy via Vue devtools.

    If there's a chance that justLocalFunction needs to be accessed later, returning it from setup function will make it easier for testing and debugging.