1. 程式人生 > 其它 >微信小程式引用自定義元件及傳值

微信小程式引用自定義元件及傳值

技術標籤:微信小程式小程式

當多個頁面需要重複使用某一功能模組時,可將該功能模組抽象成自定義元件,以便在不同的頁面中重複使用。

引用自定義元件:

建立自定義元件類似於頁面,一個自定義元件由 json wxml wxss js 4個檔案組成。

同時也可以在 wxml 檔案中編寫元件模板,在 wxss 檔案中加入元件樣式,它們的寫法與頁面的寫法類似。
專案目錄結構:
在這裡插入圖片描述

子元件的位置:components/cardItem/cardItem.js的程式碼如下

Component({
  properties: {
    // 這裡是從父元件傳遞過來的引數
  },
  data: {
    // 這裡是一些元件內部資料
  },
  methods: {
    // 這裡是一個自定義方法
    customMethod: function(){}
  }
})

cardItem.json

{
  "component": true
}

父元件引用子元件cardItem

index.json程式碼
{
  "usingComponents": {
    "component-tag-name":"../../components/cardItem/cardItem"
  }
}

index.wxml程式碼

<view class="container">
   <component-tag-name></component-tag-name>   
</view>

編寫元件樣式時,需要注意以下幾點:

#a { } /* 在元件中不能使用
[a] { } /* 在元件中不能使用
button { } /* 在元件中不能使用
.a > .b { } /* 除非 .a 是 view 元件節點,否則不一定會生效

頁面與元件之間傳值

父元件向子元件傳值( properties ),子元件向父元件傳值( this.triggerEvent() )

例如:
父頁面給子元件傳遞一個name=“Ali”,子元件給父元件傳遞一個函式方法onCreateProces,並且帶引數1212
程式碼如下:
通過wxml設定data-[引數名]傳遞引數,[引數名]只能是小寫
父元件.wxml檔案

<view >
    <children-item 
        name="Ali" 
        bind:onCreateProces="onCreateProces" 
        data-project-id="500"
     />
 </view>

父元件.js檔案

onCreateProces(event){
  let projectId = event.currentTarget.dataset.projectId//500 父元件本身的值
  let params = event.detail //1212 子元件傳過來的值
}

子元件.wxml檔案

<view catchtap="onAddClick">
     <text>{{name}}</text>
     <image  src="../../img/add.png" alt="新增"></image>
</view>

子元件.js檔案

Component({
  properties: {
    name:{
        type:String
    }
  },
  methods: {
    onAddClick(){
      //傳值給父元件  事件名 引數值
      this.triggerEvent("onCreateProces",1212)
     },
  }
})