一、props传值
props传值在WePY中属于父组件与子组件之间(包括页面与其子组件之间)传值的一种机制,包括静态传值与动态传值。
静态传值只能传递String类型,不能传递Number、Boolean、Object等其他类型。
动态传值使用`:prop`(等价于`v-bind:prop`),子组件会接收父组件的数据。
与静态传值只能通过父组件向子组件单向传值不同,动态传值包括了单向动态传值和双向动态传值。
+ 1. 单向动态传值:父组件向子组件单向动态传值(父组件可随时改变子组件中的值)。
+ 2. 双向动态传值:子组件props对象中某个属性值的修改会改变父组件data对象中对应属性的值(注意,父子组件中的这两个属性其名称可以不一致,两者通过在父组件wxml中插入子组件时在子组件标签的属性中进行映射关联)。
sync,和twoWay 这里都是单向,区别是,一个是父到子,一个是子到父。
page_parent.wpy
<btnctl :selectItemId.sync="selectItemid"></btnctl>
<script>
data = {
selectItemid:'szsaaq'
}
}
onLoad( options ) {
this.selectItemid=options.id
}
}
</script>
child.wpy组件
props = {
selectItemId:{}
}
methods = {start (m) {
console.log("选择的测试题id:"+this.selectItemId)
}}
onLoad(){
console.log(this.selectItemId)//子组件onLoad方法先于父组件执行,所以是默认值
}
二、子组件传递给父组件=》页面
采用emit
child.wpy
methods = {
start (m) {
this.$emit('parentFn',this.selectItemId);
}
}
page_parent.wpy
<child @child.user="parentFn"></child>
methods={
parentFn(e){
console.log(e)
}
}
三、`$invoke`是一个组件对另一个组件的直接调用,通过传入的组件路径找到相应组件,然后再调用其方法。
`$invoke`是一个页面或组件对另一个组件中的方法的直接调用,通过传入的组件路径找到相应组件,然后再调用其方法。
①比如,想在页面`Page_Index`中调用组件btnctl中的某个方法sendMessage:
```Javascript
this.$invoke('btnctl', 'someMethod', 'someArgs');
```
②如果想在组件A中调用组件btnctl的某个方法sendMessage:
```Javascript
this.$invoke('../btnctl', 'sendMessage', this.selectItemId);