開発プロセスでは、ページ内の特定のモジュールが繰り返し使用され、このモジュールをコンポーネントにパッケージ化して、コンポーネントをページ上のラベルの形式で直接呼び出すことができます。コンポーネントはページに似ており、カスタムコンポーネントには独自のwxml、wxss、その他のファイルがあります
カスタムコンポーネントプロセスを作成する
- プロジェクトのルートディレクトリの下にコンポーネントフォルダを作成し、そのフォルダの下にコンポーネントフォルダを作成し、コンポーネントフォルダの下に4つの対応するコンポーネントファイルを作成します。
注:各コンポーネントには、4つのファイルcomponent.wxml component.wxss component.jsoncomponent.jsがあります。
- component.wxmlコンポーネントテンプレートファイル
- component.wxssコンポーネントスタイルファイル
- component.json
{
"component": true, //告诉小程序 这是一个组件 如果当作组件使用 这个属性一定要设置为true
"usingComponents": {}//使用其他的组件
}
- component.js
Component({ //定义组件 记录了这个组件的所有逻辑任务
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
}
})
カスタムコンポーネントを使用する
これは非常にシンプルで、1つのタグフォーム<Nav> </ Nav>を直接使用するvueに似ています。
***。jsonファイルで導入
{
"usingComponents": {
"Nav" : "../components/Nav/Nav"
}
}
コンポーネントの例TencentNews Navigation
方法1
<view class="tencentNews-nav">
<view class="{
{idx == 1 ? 'active' : ''}}" bindtap="click" data-index="1">推荐</view>
<view class="{
{idx == 2 ? 'active' : ''}}" bindtap="click" data-index="2">NBA</view>
<view class="{
{idx == 3 ? 'active' : ''}}" bindtap="click" data-index="3">足球</view>
<view class="{
{idx == 4 ? 'active' : ''}}" bindtap="click" data-index="4">综合体育</view>
<view class="{
{idx == 5 ? 'active' : ''}}" bindtap="click" data-index="5">CBA</view>
</view>
data: {
idx:1
},
methods: {
click:function(e){
console.log(e.target.dataset.index)
var key = e.target.dataset.index
this.setData({
idx:key
})
}
}
方法2
<view class="tencentNews-nav">
<view
wx:for="{
{arr}}"
wx:key="id"
bindtap="click2"
data-index="{
{index}}"
class="{
{idx2 == index ? 'active' : ''}}"
>{
{item.title}}</view>
</view>
//js文件
data: {
idx2:0,
arr:[
{
id:0,
title:'推荐'
},
{
id:1,
title:'NBA'
},
{
id:2,
title:'足球'
},
{
id:3,
title:'综合体育'
},
{
id:4,
title:'CBA'
}
]
},
methods: {
click2:function(e){
console.log(e.target.dataset.index)
var key = e.target.dataset.index
this.setData({
idx2:key
})
}
}