在自組件中操作父組件的數據,父組件的數據同步改變
紅色邊框爲父組件
綠色邊框爲子組件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../../lib/vue-2.6.11.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#ele {
border: 2px solid red;
}
#children {
border: 2px solid greenyellow;
}
</style>
<title>vue-組件化</title>
</head>
<body>
<div id="ele">
<div>couter值爲:{{chmsg}}</div>
<my-cpn :cal="chmsg" @itemclick="parentClick"></my-cpn>
</div>
<template id="tmp">
<div id="children">
<button v-for="item in buttons" @click="bthClick(item)">{{item.text}}</button>
</div>
</template>
<script>
const app = new Vue({
el: "#ele",
data: {
message: "Hello everyone",
"chmsg": 0
},
methods: {
parentClick(item) {
this.chmsg = item;
}
},
components: {
"my-cpn": {
template: "#tmp",
props: {
cal: {
type: Number,
default: 0
},
},
data() {
return {
buttons: [
{id: "1", text: "+"},
{id: "2", text: "-"},
]
}
},
methods: {
bthClick(item) {
if(item.id === "1"){
this.cal++
}else{
this.cal--
}
this.$emit('itemclick', this.cal);
}
}
}
}
});
</script>
</body>
</html>
//1、子組件methods定義函數
//2、子組件動態綁定函數
//3、子組件函數emit一個自定義事件
//4、父組件動態監聽被髮射的自定義事件
//5、自定義事件被觸發時,調用父組件的處理函數