创建一个文件夹像是components之类的名字随便起,然后在该文件夹里创建组件文件夹可以在这个文件夹上右键选择新建小程序组件,也可以一个文件一个文件自己建,需要注意的是自定义组件和页面一样也是又acss,js,axml,json组成的而且js文件和json文件时有区别的js是由Comonent组成的json需要添一句"component": true,当然如果直接选择新建小程序组件就没这些事
js
- Component({
- mixins: [],
- data: {},
- props: {
- itemData: {}
- },
- didMount() {},
- didUpdate() {},
- didUnmount() {},
- methods: {},
- });
json
- {
- "component": true
- }
使用组件就不说了就直接把组件当成标签放上去行了
注册需要在使用的页面的json文件里
- {
- "defaultTitle": "页面标题",
- "usingComponents": {
- "component":"/components/component/component"
- }
- }
更改配置,每个项目配置一次就行了
选择右上角的详情

然后勾选

父组件
- 我是父组件
- <component father="123">component>
子组件
- <view>
- {{ father }}
- 我是子组件
- view>
- Component({
- data: {...},
- props: {
- father: '该参数的默认值'
- }
- })
使用props接受参数,定义的值是该字段的默认值
引用一段官方文档里的话
- 使用
ref绑定saveRef之后,会在组件初始化时触发saveRef方法。saveRef方法的参数ref为自定义组件实例,由框架传递给saveRef方法。ref同样可以用于父组件获取子组件的实例。
使用ref可以获取组件的实例,所以可以获取组件的参数
父组件
- <component ref="saveRef">component>
- <view>{{ father }}<view>
- Component({
- data: {
- father: ''
- },
- refSave (ref) {
- this.setData({
- father: this.ref.data.son
- })
- }
- })
子组件
<view>{{ son }}view>
- Component({
- data: {
- son: '子传父的参数'
- }
- })