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 there is another component calling this function and passing the parameter to ‘addItem()’.
Thanks!
Solution :
Here’s a working version of the 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.js 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>
Solution 2:
The easiest way to communicate between components is to use emit.
For example: This is the 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>