代碼
提交代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<parent></parent>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script type="text/javascript">
Vue.component('parent', {
template: '<div><child :name="name" :count="count" @add="add"/></div>',
data() {
return {
name: '句號(hào)',
count: 18
}
},
methods: {
// 父組件通過(guò) @事件名 監(jiān)聽
// count 表示事件觸發(fā)傳遞的參數(shù)
add(count) {
this.count = count
}
}
})
Vue.component('child', {
template: '<div>我是:{{name}}, 我今年 {{count}}歲。<button @click="add">加一歲</button></div>',
props: {
name: {
type: String,
default: '句號(hào)'
},
count: {
type: Number,
default: 18
}
},
methods: {
add(){
// add -> 觸發(fā)的事件名
// this.count + 1 -> 觸發(fā)事件時(shí)傳遞的參數(shù)
this.$emit('add', this.count + 1)
}
}
})
var vm = new Vue({
el: '#app',
data() {
return {}
}
})
</script>
</html>
運(yùn)行結(jié)果