1. 在子組件中通過this.$parent.event來調(diào)用父組件的方法,data參數(shù)可選
<template>
<div>
<h1>我是父組件</h1>
<child />
</div>
</template>
<script>
import child from '@/components/child';
export default {
components: {
child
},
methods: {
fatherMethod(data) {
console.log('我是父組件方法');
}
}
};
</script>
<template>
<div>
<h1>我是子組件</h1>
<button @click="childMethod(data)">點擊</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$parent.fatherMethod(data);
console.log('調(diào)用父組件方法')
}
}
};
</script>
2.父組件使用v-bind綁定一個變量(v-bind:變量名="值"),子組件用props接收(與created同級)
<template>
<div>
這是父組件
<child :parentHandler="parentHandler" />
</div>
</template>
<script>
import child from "@/components/child";
export default {
components: { child },
data() {
return {};
},
methods: {
parentHandler() {
console.log("這是父組件的方法");
},
},
};
</script>
<template>
<div>
這是子組件
<button @click="handler">這是子組件的按鈕</button>
</div>
</template>
<script>
export default {
props: {
parentHandler: {
type: Function,
default: () => {
return Function;
},
},
//parentHandler: {
// type: Object,
// default: () => {
// return {}
// },
//},
// parentHandler: {
// type: Boolean,
// default: true,
// },
// parentHandler: {
// type: Array,
// default: () => {
// return []
// },
// },
// parentHandler: {
// type: String,
// default: '',
// },
},
methods: {
handler() {
this.parentHandler();
},
},
};
</script>
3.使用$refs傳值
<template>
<div>
<h3>這是父組件</h3>
<button @click="setChildInfo">向子組件傳值</button>
<h3>這是父組件中引用的子組件</h3>
<child ref="child"></child>
</div>
</template>
<script>
//子組件地址(僅供參考),具體以實際項目目錄地址為準(zhǔn)
import child from "./Child.vue";
export default {
components: {
child: child
},
data() {
return {};
},
methods: {
// 向子組件傳值
setChildInfo() {
this.$refs.child.cInfo = "c2";
//this.$refs.child.open("c2");
}
}
};
</script>
<template>
<div>
<p>收到父組件數(shù)據(jù):{{ cInfo }}</p>
</div>
</template>
<script>
export default {
data() {
return {
cInfo: "c1"
};
},
methods: {
//open(data) {
// console.log(data);
//},
},
};
</script>
文章來源地址http://www.zghlxwxcb.cn/news/detail-612795.html
文章來源:http://www.zghlxwxcb.cn/news/detail-612795.html
到了這里,關(guān)于Vue子組件調(diào)用父組件事件的三種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!