欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 微信小程序组件传参

微信小程序组件传参

2025/4/16 15:38:41 来源:https://blog.csdn.net/weixin_46541579/article/details/147261144  浏览:    关键词:微信小程序组件传参

微信小程序组件传参感觉和vue还是挺像的

父组件向子组件传参

在小程序中父组件子组件传参,主要使用properties属性。演示下:

创建组件文件夹component,创建组件demoComponent,记得创建的时候选择组件,不是page页面

 组件代码,这里简单写了一个tab栏,动态判断绑定类名

<view class="tablist">
<view class="tabitem {{item.id==active ?'active' :''}}" wx:for="{{tablist}}"> {{item.name}}</view>
</view>

在 properties里面生命一个active,来实现当前选中项,值为number类型

// component/demoComponent/demoComponent.js
Component({/*** 组件的属性列表*/properties: {active:{type:Number}},/*** 组件的初始数据*/data: {tablist:[{id:1,name:'全部'},{id:2,name:'零食'},{id:3,name:'饮料'},],},/*** 组件的方法列表*/methods: {}
})

 

.tablist{display: grid;grid-template-columns: repeat(3,1fr);
}
.tabitem{text-align: center;padding: 10px 0;
}
.active{border-bottom: 3px solid blue;
}

在页面中使用的时候,需要在json中声明

{"usingComponents": {"demoComponent":"/component/demoComponent/demoComponent"}
}

这里传入active为2 

<demoComponent active='2' />

当组件渲染的时候,第二项被赋上active样式

子向父传参 

使用自定义事件,triggerEvent。这点和vue非常相似,传入两个参数,第一个参数为自定义事件名,第二个为传递的值。演示下,稍微修改下组件代码

绑定事件

<view class="tablist">
<view bind:tap="sendInfo" class="tabitem {{item.id==active ?'active' :''}}" wx:for="{{tablist}}"> {{item.name}}</view>
</view>

 使用triggerEvent来传递数据(组件js代码,写在methods中)

 sendInfo(){const data={name:'zs',age:12}this.triggerEvent('sendData',data)}

父组件接受

<demoComponent active='2' bind:sendData="getData"/>getData(e){console.log('e',e.detail);},

当点击组件的时候,可以从控制台看到拿到从子组件传递的值了

跨组件传参 

建议使用全局变量,在微信小程序中,全局变量写在app.js中globalData对象里面,在页面中通过getApp() 方法即可访问到app.js里面的方法和全局变量。全局方法不需要写在methods里面,和globalData同一级的

  globalData: {myInfo:{name:'aaaaa',age:1231212}},getMethosFunc(){console.log('获取app.js的方法');}
 onLoad(options) {const app=getApp();console.log('myinfo',app.globalData.myInfo);app.getMethosFunc();},

end 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词