1.父组件给子组件传值(props)
props
父组件
<import name="son" src="./son"></import><template><div class="father"><text>父组件</text><son say="{{say}}" prop-object="{{obj}}"></son></div>
</template><script>export default {data(){return {say:'hello'obj:{name:'child-demo'}}}}
</script>
子组件
<template><div class="son"><text>子组件</text><text>{{ say }}</text><text>{{ propObject.name }}</text></div>
</template><script>export default {props: ['say', 'propObject'],onInit() {console.log('父组件传过来的值:', this.say, this.propObject)}}
</script>
2.子组件给父组件传值(emit, dispath, on)
emit
子组件
<template><div class="son"><text>子组件</text><text onclick="son">点击子组件</text></div>
</template><script>
export default {data: {},son() {this.$emit('son')}
}
</script>
父组件
<import name="son" src="./son.ux"></import><template><div class="father"><text>父组件</text><son onson="fatherFunc"></son></div>
</template><script>
export default {data: {},fatherFunc() {console.log('父组件方法:子组件被点击')}
}
</script>
dispath
子组件
<template><div class="son"><text onclick='delHandler'>子组件age:{{compAge}}</text></div>
</template><script>
export default {data(){return{compAge:9}},delHandler(){this.$dispatch('dispatchEvt',{num:this.compNum})},
}
</script>
父组件
<import name="son" src="./son.ux"></import><template><div class="father"><text>父组件num:{{num}}</text><son num="{{num}}"></son></div>
</template><script>
export default {data() {return {num:20,}},onInit(){this.$on('dispatchEvt',this.dispatchEvt)},dispatchEvt(evt){this.num = evt.detail.num},
}
</script>
on
子组件
<import name="son" src="./son.ux"></import><template><div class="son"><text>我是子组件age:{{compAge}}</text></div>
</template><script>
export default {data(){return{compAge:null}},onInit(){this.$on('broadevt',this.broadevt)},broadevt(evt){this.compAge = evt.detail.age}
}
</script>
父组件
<import name="son" src="./son.ux"></import><template><div class="father"><text onclick="evtTypeEmit">父组件age:{{age}}------触发$broadcast()函数</text><son></son></div>
</template><script>
export default {data() {return {age:18,}},evtTypeEmit(){this.$broadcast('broadevt',{age:19})},
}
</script>