I have two components: child Dog
and parent App
. Inside the App
I'm trying to change Dog
's properties hasName
and name
on button click. However I get an error: hasName
is undefined.
Child component:
Dog.vue
<template>
<div>
<div>A Dog</div>
<div v-if="hasName">Name: {{ name }}</div>
</div>
</template>
<script>
export default {
data: function () {
return {
hasName: false,
name: "",
};
},
};
</script>
Parent component:
App.vue
<template>
<div id = "app">
<img alt="Vue logo" src="./assets/logo.png" />
<Dog />
<button @click="handleClick">Click</button>
</div>
</template>
<script>
import Dog from "./components/Dog.vue";
export default {
name: "App",
components: {
Dog,
},
methods: {
handleClick: function () {
this.Dog.hasName = true;
this.Dog.name = "Jerry";
},
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
I get the error:
Cannot set property 'hasName' of undefined
Vue fiddle: https://codesandbox.io/s/upbeat-resonance-b65pd?file=/src/App.vue