簡單的例子 沒有多餘代碼,
父傳子
<template>
//父組件 引用子組件aaa 兩種寫法傳遞num1,num2
<div>
<aaa v-bind:father1="num1" :father2="num2"></aaa>
</div>
</template>
<script>
import aaa from './aaa'
export default {
data () {
return {
num1:'111',
num2:'222',
}
},
components:{
aaa
}
}
</script>
<style scoped>
</style>
子組件
<template>
//兩種prop接收寫法,
<div>
<h3>子組件</h3>
<h2>{{father1}}</h2>
<h2>{{father2}}</h2>
</div>
</template>
<script>
export default {
// props:['father1','father2']
props:{
father1:String,
father2:String
}
}
</script>
子傳父
點擊’獲取子組件的值’頁面顯示444
<template>
<div>
<h3>父組件傳的值</h3>
<h2>{{father1}}</h2>
<h2>{{father2}}</h2>
<h3 @click="fn">獲取子組件的值</h3>
</div>
</template>
<script>
export default {
// props:['father1','father2']
props:{
father1:String,
father2:String
},
data() {
return {
childNum:'444'
}
},
methods: {
fn(){
this.$emit('listenEvent',this.childNum)
}
},
}
</script>
<template>
<div class="hello">
<!-- <div>練習:{{num}}</div> -->
<aaa v-bind:father1="num1" :father2="num2" @listenEvent="fn"></aaa>
<h3>{{num3}}</h3>
</div>
</template>
<script>
import aaa from './aaa'
export default {
data () {
return {
num1:'111',
num2:'222',
num3:'',
}
},
components:{
aaa
},
methods: {
fn(params){
this.num3 = params
}
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>