一、template的使用
1.注冊模板:在app.json里面注冊模板temlate/public,生成模板wxml,wxss,js,json等系列頁面,也可以自己創建這些文件。
2.編寫模板
<1>無數據傳參的模板
<template name="hello"> <view>hello world!</view> </template>
<2>帶數據傳參的模板
<template name="hello2"> <view wx:for='{{list}}' wx:key="{{key}}">hello world!{{item.name}}</view> </template>
3.模板的使用
<1>引入模板頁面
<import src="../template/hello/hello.wxml"/>
<2>使用模板
<view> <template is="hello" ></template> <template is="hello2" data="{{list}}"></template> </view>
注意:
1.引用的template傳入的data參數名字(data="{{list}}")要與注冊時template使用的(wx:for="{{list}}" 時)的參數名字相同
2.template的data是有作用域的,外部參數通過data傳入注冊的template里面,只作用與template局部,可重復引用
二、自定義組件的使用
1.注冊組件:在app.json里面注冊模板components/myComponent/myComponent, 生成模板wxml,wxss,js,json等頁面,也可以自己創建這些文件。
2.編輯組件
wxml:
<view class="inner"> <text>hi,I am {{ uname }}</text> </view>
json:
{
"component": true
}
js:
const app = getApp()
Component({
properties: {
// 這里定義父組件傳值的屬性
uname: {
type: String,
value: '張三', //默認值設置
}
},
data: {
// 這里是組件內部數據
someData: {}
},
methods: {
customMethod(){
//子組件傳值給父組件
this.triggerEvent("toParent","hello world! I am learning 微信小程序")
}
}
})
3.組件的使用:在要引入的組件的json文件中加入
{
"usingComponents": {
//組件名(自定義)以及組件所在路徑
"myComponent": "../../components/myComponent/myComponent"
}
}
在要引入的組件的wxml文件中加入
<view> <myComponent id="myComponent" uname="{{username}}" bind:toParent="getSome"></myComponent> </view>
引入組件的js:
data:{
username:'木蘭'
},
getSome(e){
var data=e.detail //從子組件獲得的數據
}
