父组件给子组件传值
parent.wxml:<view><child title="我是父组件传进来的标题"/><child /></view>child.wxml:<view class="child">{{title}}</view>*在child.js的properties接收父组件传给子组件的数据:properties: {// title:String (第一种写法)title:{ // (第二种写法)type:String,value:'我是子组件默认的title' //当父组件没有传递参数的时候,使用value的值为默认值}}
父组件调用子组件的方法
先给子组件定义一个id父组件获取子组件的实例:var header=this.selectComponent("#head")header.方法名() 执行子组件的方法parent.wxml:<view><child id="header"/><button size="mini" bindtap="ParentGetChild_Method">父组件调用子组件的方法</button></view>child.wxml:<view class="child">{{title}}</view>
child.js:Component({properties: {title:{type:String,value:'我是子组件默认的title'}},data: {},methods: {run(){console.log('我是子组件的run方法')}}})
parent.js:ParentGetChild_Method(){var header=this.selectComponent('#header')header.run()}
子组件调用父组件的方法
1. 在子组件的方法中:this.triggerEvent('parent') 2. 在父组件调用子组件:<child bindparent="run"> //run即父组件中被子组件调用的方法*this.triggerEvent('参数1'),参数1是自定义的,但在父组件调用子组件的时候,必须bind+参数1
child.wxml:<button size="mini" bindtap="ChildGetParent_method">子组件调用父组件的方法</button>parent.wxml:<child bindparent="isParent"/>
child.js:Component({properties: {},data: {},methods: {ChildGetParent_method(){this.triggerEvent('parent')}}})parent.jsisParent(){console.log('我是父组件的方法')}