Search code examples
vue.jscomponents

Vuej.s: How pass variable to component attribute


How can i pass variable to component in Vue.js (not via props)? Is that possible?

Here app.js:

import PlayingField from '../app/components/PlayingField'
import GameConfig from '../../gameConfig'

new Vue({
    el: '#app',
    components: {
        playingfield: PlayingField,
    },
    data: {
        gameConfig: GameConfig
    }
});

In game config is json and there is key 'maxUniqueCards' and this value i want in component playingField... No in template but in attribute to next work with it... (generate cards, order.... just for usage in playingField component methods...)


Solution

  • You can use the $parent property:

    <template>
      <div>
        App
        <input type="text" v-model="propTest">
        <Child />
      </div>
    </template>
    
    <script>
    import Child from '@/components/Child.vue';
    
    export default {
      name: 'App',
      components: { Child },
      data: () => ({
        propTest: 'abc',
      }),
    };
    </script>
    
    
    <template>
      <div>
        child
        <button @click="test">Test</button>
      </div>
    </template>
    
    <script>
    export default {
      name: 'Child',
      methods: {
        test() {
          console.log(this.$parent.propTest);
        },
      },
    };
    </script>
    
    

    Be careful with this property, you must use in edge cases: https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-the-Parent-Component-Instance