简体   繁体   中英

How to access Vue component data from component method

I'm a beginner to Vue, and I'm confused about why I cannot access a data property from within a method both on the same component. Every time I try to access my data by using 'this.items', it returns that 'items is undefined'.

I've tried changing the syntax of how I write the methods (I initially used an arrow function, but learning that it changes 'this', switched to a regular function definition), but it is still returning items as undefined.

Here is my full component with template:

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

<script>

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

            addItem: function(t) {

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


This is just a simple todo list, and I have another component calling this function and passing the parameter to 'addItem()'.

Thanks!

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM