Search code examples
javascriptcomponentsvuejs2state-management

Vue js - source available to component


I have created a source in my main app.js file

let source = {
    selectedTalent: 0,
};


 var vm = new Vue({
 el: '#app',
 components:{
  Navigation:navigation,

I want the source to be available in my navigation component. I aways get a not defined error.

How do I get this to work. Do I have to pass as a prop? I though this would be globally available as 'source'

My component is imported like this as I am using a custom webpack

import navigation from './components/nav.vue';

This is the only difference I can see from the example in the docs.


Solution

  • You should export and import that source object correctly, otherwise its scope is within the app.js script. That scoping is pretty much what Webpack does.

    Example:

    source.js

    export default let source = {
        selectedTalent: 0,
    };
    

    navigation.component.js

    import source from '../path/to/source/'
    
    /* your code for the component here */
    

    And then you could avoid declaring source in your app.js as you seem not to be using it in there.