admin管理员组

文章数量:1297015

How to call Vue instance in chrome console, if it created in a separated file new Vue({ ... }). Like console.log(vm.user.id)

new Vue({
  el: '#app',
  data: {
    message: {
      id: 1,
      title: 'TEST VUE'
    }
  }    
});

How to call Vue instance in chrome console, if it created in a separated file new Vue({ ... }). Like console.log(vm.user.id)

new Vue({
  el: '#app',
  data: {
    message: {
      id: 1,
      title: 'TEST VUE'
    }
  }    
});

Share edited Aug 31, 2020 at 6:15 Evgen002 asked Aug 31, 2020 at 4:51 Evgen002Evgen002 351 silver badge7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

If you have the Vue DevTools installed it will create aliases for your Vue instances when you click on them:

Note the light text to the right of the ponent name. It may be hard to see on some screens.

In the picture above, $vm1 and $vm2 are accessible in the console and will refer to the corresponding Vue instances.

As you click around in the DevTools these aliases will change. $vm0 will refer to the last ponent you clicked on.

The best way to do this is by using the Vue Chrome extension as described by @skritle. You also get nice UI with bells and whistles to look at the data, puted properties etc if that's what you need.

However, I've had to do this in environments which didn't have the extension. In those scenarios, you can just add the instance to the global object window (browser) or global (nodejs).

const app = new Vue({...});
window.$appRef = app; // Remove this line for release

Then in load the app in the browser and you can access it in the console :

console.log($appRef)

This should only be used as an emergency escape hatch because it pollutes the global object (potentially causing name collisions and memory leaks) and should be cleaned up after use. You can also wrap it in an if condition to ensure it is used only during development

if (
    process.env.NODE_ENV !== 'production' &&
    process.env.NODE_ENV !== 'test' &&
    typeof console !== 'undefined'
){
    window.$appRef = app;
}

Question already has it's accepted answer, but it's worth mentioning the remended pattern to capture different instance for vue - https://v2.vuejs/v2/guide/instance.html#Creating-a-Vue-Instance

Just make your own custom variable for different vue instances

// Use var to mark this variable a global, make sure it's wrapped directly to global execution context, so that you can get it at window scope
var vueInstance1 = new Vue({ 
  el: '#app1',
  data: { title: 'Vue Instance 1' }
})
var vueInstance2 = new Vue({
  el: '#app2',
  data: { title: 'Vue Instance 2' }
})

console.log('Instance 1- ', vueInstance1.title ) // Easily access to instance 1
console.log('Instance 2- ', vueInstance2.title ) // Easily access to instance 2
<script src="https://cdnjs.cloudflare./ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app1">{{ title }}</div>
<div id="app2">{{ title }}</div>

本文标签: