Vue中子組件調用父組件的方法
相關Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../js/vue-2.4.0.js"></script>
<style>
</style>
</head>
<body>
<div id="app">
<!--父組件可以在引用子組件的時候,通過屬性綁定的形式(v-bind:),-->
<!--把需要傳遞給子組件的數據,以屬性綁定的形式傳遞到子組件中 給子組件使用-->
<com2 @func="show"></com2>
</div>
<template id="temp1">
<div>
<h1>這是子組件</h1>
<input type="button" value="這是子組件按鈕 點擊后觸發父組件的func方法"
@click="myclick"
>
</div>
</template>
<script>
var com2 = {
template: '#temp1',
data: function () {
return {
sonmsg: {name: '大頭兒子', age: 6}
}
},
methods: {
myclick: function () {
//當點擊子組件的按鈕的時候如何拿到父組件的func方法 並調用
//$emit() 原意:觸發
//第二個參數可以傳參
this.$emit('func', this.sonmsg);
console.log('ok');
}
}
}
var vm = new Vue({
el: '#app',
data: {
datamsgFromSon: null
},
methods: {
show: function (data) {
console.log("調用了父組件的func,並且data為:" + data);
console.log(data);
this.datamsgFromSon = data;
}
},
components: {
com2: com2
}
});
</script>
</body>
</html>
