I have a scenario where I have a button in my parent component App.vue that triggers an event on a child component, passing an incremental number each time the button is clicked. Currently, I am achieving this by passing the value as a prop and watching for changes in the child component using watch: {
While this method works well, as a newcomer to Vue.js, I am curious if there is a more efficient or recommended way to accomplish this?
App.vue
<template>
<div id="app">
<button @click="myMethod">To child</button>
<Mycomponent :myProp="count" />
</div>
</template>
<script>
import Mycomponent from "./components/Mycomponent";
export default {
name: "App",
components: {
Mycomponent
},
data() {
return {
count: 0
};
},
methods: {
myMethod() {
this.count++;
}
}
};
</script>
Mycomponent.vue
<template>
<div>
{{myNumber}}
</div>
</template>
<script>
export default {
name: "Mycomponent",
props: {
myProp: {
type: Number
}
},
data() {
return {
myNumber: 0
};
},
watch: {
myProp: {
deep: true,
immediate: true,
handler(newValue) {
try {
console.log("Print my value in the consule: ", newValue);
this.myNumber = newValue
} catch (err) {
console.log("no data yet ...");
}
}
}
}
};
</script>
UPDATED EXAMPLE FOR REACHING PROP IN CHILD COMPONENT
<template>
<div>
// what if I dont want to display myProp in the template? Just store the data
{{myProp}}
<button @click="myMethod">Method</button>
</div>
</template>
<script>
export default {
name: "Mycomponent",
props: {
myProp: {
type: Number
}
},
methods: {
myMethod() {
console.log("print myProp ", this.myProp);
}
}
};
</script>
But what about if I don't want to display the value. Just use the prop as data?