Hey I am really new to VUE and for this project I have a button on one page which should trigger or call the function of another page. Everyone will be like why don't you have the button and function on same page as I am trying to learn basic part of how to call function of different page and then implement on my project. I am trying to make it easier and clear while I am asking question.
When I call the method function of chairPage.vue from homePage.vue, it throws an error saying world not defined on homePage.vue. Can anyone please explain why I am getting this error and what's the best way to solve this.
I have two pages one is homePage.vue and another one is chair.Vue. I have a button on homePage.vue which should call the method function of chairPage.vue.
Home Page
<template>
<div id="homepage">
<b-button variant="info" @click="buttonClicked()">Click</b-button>
<chairComponent ref="world"/>
</div>
</template>
<script>
import chairComponent from '@/components/chair.vue';
export default {
props: [],
methods:{
buttonClicked(){
this.$refs.world.hello();
}
}
}
</script>
Chair Page
<template>
<div id="chairComponent">
<p v-if="displayText == '1'"> HELLO WORLD </p>
</div>
</template>
<script>
export default {
props: ['world'],
data(){
return{
displayText:'',
}
},
methods:{
hello(){
console.log('inside child component hello function');
this.displayText = '1';
}
}
}
</script>
CodePudding user response:
You can pass props to your child component, and there watch on props and call function:
Vue.component('Chair', {
template: `
<div id="chairComponent">
<p v-if="displayText == '1'"> HELLO WORLD </p>
</div>
`,
props: ['world'],
data(){
return{
displayText:'',
}
},
methods:{
hello(){
console.log('inside child component hello function');
this.displayText = '1';
}
},
watch: {
world() {
if (this.world) this.hello()
}
}
})
new Vue({
el: '#demo',
data() {
return {
val: null
}
},
methods:{
buttonClicked(){
this.val = true
}
}
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>
<div id="demo">
<div id="homepage">
<b-button variant="info" @click="buttonClicked">Click</b-button>
<chair :world="val" />
</div>
</div>
CodePudding user response:
You can $emit from children to parent https://vuejs.org/v2/guide/components-custom-events.html
Child
hello () {
...//yours code
this.$emit('customEvent', someValue)
}
Parent
<template>
<child
@cutomEvent="function"
/>
<template>
