划重点:
$emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数。
子组件:
1 <template> 2 <div> 3 <!-- <div>子页面</div> --> 4 <div class="mess"> 5 <div v-for="(item,index) in message" :key="index"> 6 {{item.id}} 7 </div> 8 </div> 9 <div> 10 <button @click="addFont()"> 点击+ </button> 11 <button @click="minus()"> 点击- </button> 12 </div> 13 </div> 14 </template> 15 <script> 16 export default { 17 name:"shopping", 18 props: { 19 message:{ 20 type : Array, 21 default: function() { 22 return [] 23 } 24 }, 25 }, 26 data() { 27 return { 28 fontSize:0, 29 } 30 }, 31 methods: { 32 addFont(){ 33 if(this.fontSize <= 0){ 34 this.fontSize =1 ; 35 }else{ 36 this.fontSize++; 37 } 38 this.$emit(‘addnum‘,this.fontSize); 39 }, 40 minus(){ 41 if(this.fontSize <= 0){ 42 this.fontSize = 0 43 }else{ 44 this.fontSize-- 45 } 46 this.$emit(‘minusNum‘, this.fontSize); 47 } 48 }, 49 } 50 </script>
$emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件
父组件:
1 <template> 2 <div class="comment"> 3 <div>comment</div> 4 <div class="btn"> 5 <router-link :to=‘{name:"shopping", query: { id: userID}}‘ @click="tiao()" tag="span" >跳转</router-link> 6 </div> 7 <div class="num">{{num}}</div> 8 <shopping :message="HelloWorld" @addnum=‘addNum‘ @minusNum="minusNum"></shopping> 9 </div> 10 </template> 11 <script> 12 import shopping from ‘../shopping/shopping‘ 13 export default { 14 name:"comment", 15 components:{shopping}, 16 data() { 17 return { 18 userID:1, 19 num:0, 20 HelloWorld:[ 21 { id:"a"}, 22 {id:"b"}, 23 {id:"c"}, 24 ] 25 } 26 }, 27 methods: { 28 addNum(data){ 29 this.num = data 30 }, 31 minusNum(data){ 32 this.num = data 33 } 34 }, 35 } 36 </script>
父组件通过@event监听并接收参数。