[Vuejs]-How to access Vue component data from component method

0👍

Here’s a working version of your code, demonstrating how to display items and add a new element to the items array from the UI:

https://codesandbox.io/embed/vue-template-7j0xj?fontsize=14

Or if you prefer, the Vue component code is also attached below:

<template>
    <div id="app">
        <div>Hello</div>
        <ul v-if="items">
            <li v-for="(item, index) in items" :key="index">
              <div>{{item}}</div>
            </li>
        </ul>
        <div @click="addItem('Something More')">Click to Add Something</div>
    </div>
</template>

<script>

export default {
  name: "App",
  data() {
    return {
      items: ['foo','bar','baz']
    };
  },
  methods: {
    addItem: function(t) {
      this.items.push(t)
    }
  },
};
</script>

0👍

The easiest way to communicate between components is to use emit.

For example: This is your parent or child component it doesnt matter for this method.

<template>
    <div>
        <ul>
            <li v-for="(item, index) in items" :key="index">
            </li>
        </ul>
    </div>
</template>

<script>

    export default {
        data() {
            return {
                'items': []
            };
        },

        mounted(){
            this.eventHub.$emit('add_item:method', this.addItem);
        },

        methods: {

            addItem: function(t) {

                this.items.push(t)
            }
        },
    }
</script>

and the listen to event method other component for this way.

<template>

</template>

<script>

    export default {

        mounted(){
            this.eventHub.$on('add_item:method');
        },
    }
</script>

Leave a comment