Marshall Davis
Marshall Davis

Reputation: 3650

Global variable with vue instance not defined

I'm defining the Vue.js instance like this in app.js:

const vm = new Vue({
    el: '#app',
    data: {
        page: 'welcome'
    }
});

and using Laravel's default webpack script:

mix.js('resources/assets/js/app.js', 'public/js')
  .sass('resources/assets/sass/app.scss', 'public/css');

Vue is loading correctly as the components are displaying and the Vue developer plugin is showing appropriate data.

However, in the developer console and in scripts on the page vm is not defined.
For instance on the page that is loading a Vue component

<script>
  console.log(vm); // Error: vm is not defined.
</script>

How do I access the Vue instance? I want to set a one of its data properties.

Upvotes: 1

Views: 3260

Answers (2)

acdcjunior
acdcjunior

Reputation: 135862

To have flexibility and import with any name, you can use default exports.

In app.js:

export default new Vue({
    el: '#app',
    data: {
        page: 'welcome'
    }
});

In other .js files:

import whateverName from './app';

Naturally, adjusting the ./app depending on where the file is at.

Upvotes: 3

Marshall Davis
Marshall Davis

Reputation: 3650

I was able to use

export {
  vm
};

require('./main');

and in main.js

import {vm} from './app';

Upvotes: 3

Related Questions