【微信小程序】頁面跳轉和Template

1. 頁面跳轉

1.1 tabBar跳轉

在 app.json 中

"tabBar": {
    "color": "#b7b7b7",
    "selectedColor": "#333333",
    "borderStyle": "black",
    "backgroundColor": "#ff0",
    "list": [
      {
        "pagePath": "pages/index/index",
        "iconPath": "image/12.png",
        "selectedIconPath": "image/11.png",
        "text": "主頁"
      },
      {
        "pagePath": "pages/category/category",
        "iconPath": "image/22.png",
        "selectedIconPath": "image/21.png",
        "text": "分類"
      },
      {
        "pagePath": "pages/cart/cart",
        "iconPath": "image/32.png",
        "selectedIconPath": "image/31.png",
        "text": "購物車"
      },
      {
        "pagePath": "pages/user/user",
        "iconPath": "image/42.png",
        "selectedIconPath": "image/41.png",
        "text": "我的"
      }
    ]
  },

1.2 navigator 標籤

在 html 頁面

<view class="my-item">
   <navigator url="/pages/address/address">地址管理</navigator>
</view>
<view class="my-item">
   <navigator url="/pages/user/mytest/mytest">我的測試</navigator>
</view>
<view class="my-item">
   <navigator url="/pages/user/ontest/ontest">事件測試</navigator>
</view>
<view class="my-item">
   <navigator url="/pages/user/logintest/logintest">登錄測試</navigator>
</view>

1.3 wx.navigateTo(Object object)

仙人指路

保留當前頁面,跳轉到應用內的某個頁面。但是不能跳到 tabbar 頁面。使用 wx.navigateBack 可以返回到原頁面。小程序中頁面棧最多十層。

在 js 中

防止 this 的指針改變,可以使用 箭頭函數 =>

onShow: function () {
  let that = this;
  let userInfo = wx.getStorageSync('userInfo');
  if (!userInfo) {
	  wx.navigateTo({
	 	  url: "/pages/authorize/authorize"
    })
  } else {
	  that.setData({
		  thumb: userInfo.avatarUrl,
		  nickname: userInfo.nickName
	  })
  }
},

1.4 wx.redirectTo(Object object)

仙人指路

關閉當前頁面,跳轉到應用內的某個頁面。但是不允許跳轉到 tabbar 頁面。

示例代碼

wx.redirectTo({
  url: 'test?id=1'
})

1.5 wx.switchTab(Object object)

跳轉到 tabBar 頁面,並關閉其他所有非 tabBar 頁面

wx.switchTab({
  url: '/index'
})

1.6 頁面跳轉時,傳參數

let index = 1;
wx.navigateTo({
    url: "/pages/authorize/authorize?index=" + index;
})

/pages/authorize/authorize.js

  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function (options) {
    console.log(options)
  },
/**
會打印:{index: "1"}
*/

1.7 輪播圖跳轉,事件委託

currentTarget 與 target 的區別
currentTarget :觸發事件的元素
target:當前的元素

<!-- 輪播圖 -->
<swiper 
	class="swiper" 
    catchtap="carouselToDetail"
	indicator-dots="{{indicatorDots}}" 
	autoplay="{{autoplay}}" 
	interval="{{interval}}" 
	duration="{{duration}}" 
	circular="{{circular}}">
       <block wx:for="{{imgUrls}}" wx:key="url">
           <swiper-item>
               <image data-id="{{item.xxxid}}" src="{{item.url}}"/>
           </swiper-item>
       </block>
</swiper>
//點擊輪播圖
carouselToDetail: function(event){
	console.log(event);
}
//xxxid 的數據 在 target 中

2. json 配置文件

2.1 全局配置app.json

{
  "pages": [
    "pages/index/index",
    "pages/second/index",
  ],
  "window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fa0",
    "navigationBarTitleText": "勇勇果城",
    "navigationBarTextStyle": "white"
  },
  "tabBar": {
    "color": "#b7b7b7",
    "selectedColor": "#333333",
    "borderStyle": "black",
    "backgroundColor": "#ff0",
    "list": [
      {
        "pagePath": "pages/index/index",
        "iconPath": "image/12.png",
        "selectedIconPath": "image/11.png",
        "text": "主頁"
      },
      {
        "pagePath": "pages/user/user",
        "iconPath": "image/42.png",
        "selectedIconPath": "image/41.png",
        "text": "我的"
      }
    ]
  },
  "sitemapLocation": "sitemap.json"
}

2.2 局部配置

每個頁面對應的 json文件
不需要寫 “window”: {}

{
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fa0",
    "navigationBarTitleText": "勇勇果城",
    "navigationBarTextStyle": "white"
}

3. swiper

詳細請看官網

滑塊視圖容器。其中只可放置swiper-item組件,否則會導致未定義的行爲。

Page({
	data: {
		signin: 0,
		imgUrls: [
			{ url: '/image/swipe1.jpg' },
			{ url: '/image/swipe2.jpg' },
			{ url: '/image/swipe3.jpg' },
			{ url: '/image/swipe4.jpg' }
		],
		indicatorDots: true,
		autoplay: true,
		interval: 3000,
		duration: 800,
		circular: true
		}
})
<!-- 輪播圖 -->
<swiper 
	class="swiper" 
	indicator-dots="{{indicatorDots}}" 
	autoplay="{{autoplay}}" 
	interval="{{interval}}" 
	duration="{{duration}}" 
	circular="{{circular}}">
       <block wx:for="{{imgUrls}}" wx:key="{{index}}">
           <swiper-item>
               <image src="{{item.url}}"/>
           </swiper-item>
       </block>
   </swiper>
.swiper {
  height: 400rpx;
  width: 100%;
  margin-top: 100rpx;
}
.swiper image {
  height: 100%;
  width: 100%;
}

4. Template模塊基本使用

詳細請到官網
模板
WXML提供模板(template),可以在模板中定義代碼片段,然後在不同的地方調用。

4.1 定義模板

使用 name 屬性,作爲模板的名字。然後在內定義代碼片段,如:

<!--
  index: int
  msg: string
  time: string
-->
<template name="msgItem">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>

4.2 使用模板

使用 is 屬性,聲明需要的使用的模板,然後將模板所需要的 data 傳入,如:

<template is="msgItem" data="{{...item}}"/>
Page({
  data: {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
    }
  }
})

is 屬性可以使用 Mustache 語法,來動態決定具體需要渲染哪個模板:

<template name="odd">
  <view> odd </view>
</template>
<template name="even">
  <view> even </view>
</template>

<block wx:for="{{[1, 2, 3, 4, 5]}}">
  <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>
</block>

4.3 模板的作用域

模板擁有自己的作用域,只能使用 data 傳入的數據以及模板定義文件中定義的
< wxs /> 模塊。

4.4 Template 實例

實例1

<import src="/template/scrollView/scrollView.wxml" />

<scroll-view class='scrollView' scroll-y>
  <!-- 循環打印模板 -->
  <view wx:for="{{ listData }}" bindtap='itemOnClick' data-id="{{item.id}}" class='itemView' wx:key="{{index}}">
    <template is="scrollViewList" data="{{ item }}" />
  </view>
</scroll-view>
<!-- scrollView模板 -->
<template name="scrollViewList">
  <!-- 循環打印列表 -->
  <!-- <view wx:for="{{ listDataHot }}" class='itemView'> -->
    <!-- 文字部分 -->
    <view class='itemViewContent'>
      <!-- 標題 -->
      <view class='contentTitle'>{{ item.title ? item.title : "無數據" }}</view>
      <!-- 內容簡介 -->
      <view class='contentIntroduction'>{{ item.content ? item.content : "無簡介"  }}</view>
    </view>
    <!-- 圖片部分 -->
    <view class='itemViewImg'>
      <image src='{{item.imgUrl}}'></image>
    </view>
  <!-- </view> -->
</template>

實例2

data: {
    movieList : [
      {
        id: 1,
        movieImg: "/image/swipe1.jpg",
        name: "霸王別姬",
        year: "1993",
        director: "陳凱歌",
        rating: "9.6"
      },{
        id: 2,
        movieImg: "/image/swipe1.jpg",
        name: "千與千尋",
        year: "2001",
        director: "宮崎駿",
        rating: "9.2"
      },{
        id: 33,
        movieImg: "/image/swipe1.jpg",
        name: "阿甘正傳",
        year: "1994",
        director: "羅伯特·澤米吉斯",
        rating: "9.5"
      },{
        id: 444,
        movieImg: "/image/swipe1.jpg",
        name: "這個殺手不太冷",
        year: "1994",
        director: "呂克·貝鬆",
        rating: "9.4"
      }
    ]
  },
<view>
  <block wx:for="{{movieList}}" wx:key="{{index}}">
      <!-- <template is="movielist" data="{{...movieList[index]}}"/>  -->
      <template is="movielist" data="{{...item}}"/> 
  </block>
</view>



<template name="movielist">
  <view class="moviesContainer">
    <text hidden="ture">{{id}}</text>
    <image class="movieImg" src="{{movieImg}}"></image>
    <view class="movie_detail">
      <text class="movie_name">{{name}}</text>
      <text class="movie_year">年份:{{year}}</text>
      <text class="movie_director">導演:{{director}}</text>
    </view>
    <text class="movie_rating">{{rating}}</text>
  </view>
</template>

5. 列表渲染

5.1 數據暴露及引入

/datas/list-data.js

let list_data = [
  { url: '/image/swipe1.jpg' },
  { url: '/image/swipe2.jpg' },
  { url: '/image/swipe3.jpg' },
  { url: '/image/swipe4.jpg' }
];

//將數據暴露出去
module.exports = (list_data);

/pages/index/index.js

使用 require 引入的時候
let datas = require(’/datas/list-data.js’);
會報錯
module “pages/index/datas/list-data.js” is not defined
只能使用相對路徑
let datas = require(’…/…/datas/list-data.js’);

let datas = require('../../datas/list-data.js');
Page({
	data: {
		signin: 0,
    	imgUrls: datas,
    	...

5.2 列表渲染

列表渲染

wx:for

在組件上使用 wx:for 控制屬性綁定一個數組,即可使用數組中各項的數據重複渲染該組件。
默認數組的當前項的下標變量名默認爲 index,數組當前項的變量名默認爲 item

<view wx:for="{{array}}">
  {{index}}: {{item.message}}
</view>
Page({
  data: {
    array: [{
      message: 'foo',
    }, {
      message: 'bar'
    }]
  }
})

使用 wx:for-item 可以指定數組當前元素的變量名,

使用 wx:for-index 可以指定數組當前下標的變量名:

<view wx:for="{{array}}" wx:for-index="idx" wx:for-item="itemName">
  {{idx}}: {{itemName.message}}
</view>

wx:for 也可以嵌套,下邊是一個九九乘法表

<view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="i">
  <view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="j">
    <view wx:if="{{i <= j}}">
      {{i}} * {{j}} = {{i * j}}
    </view>
  </view>
</view>

block wx:for
類似 block wx:if,也可以將 wx:for 用在 block 標籤上,以渲染一個包含多節點的結構塊。例如:

<block wx:for="{{[1, 2, 3]}}">
  <view> {{index}}: </view>
  <view> {{item}} </view>
</block>

wx:key
如果列表中項目的位置會動態改變或者有新的項目添加到列表中,並且希望列表中的項目保持自己的特徵和狀態(如 input 中的輸入內容,switch 的選中狀態),需要使用 wx:key 來指定列表中項目的唯一的標識符。

wx:key 的值以兩種形式提供

字符串,代表在 for 循環的 array 中 item 的某個 property,該 property 的值需要是列表中唯一的字符串或數字,且不能動態改變。
保留關鍵字 *this 代表在 for 循環中的 item 本身,這種表示需要 item 本身是一個唯一的字符串或者數字。
當數據改變觸發渲染層重新渲染的時候,會校正帶有 key 的組件,框架會確保他們被重新排序,而不是重新創建,以確保使組件保持自身的狀態,並且提高列表渲染時的效率。

如不提供 wx:key,會報一個 warning, 如果明確知道該列表是靜態,或者不必關注其順序,可以選擇忽略。

示例代碼:

<switch wx:for="{{objectArray}}" wx:key="unique" style="display: block;"> {{item.id}} </switch>
<button bindtap="switch"> Switch </button>
<button bindtap="addToFront"> Add to the front </button>

<switch wx:for="{{numberArray}}" wx:key="*this" style="display: block;"> {{item}} </switch>
<button bindtap="addNumberToFront"> Add to the front </button>
Page({
  data: {
    objectArray: [
      {id: 5, unique: 'unique_5'},
      {id: 4, unique: 'unique_4'},
      {id: 3, unique: 'unique_3'},
      {id: 2, unique: 'unique_2'},
      {id: 1, unique: 'unique_1'},
      {id: 0, unique: 'unique_0'},
    ],
    numberArray: [1, 2, 3, 4]
  },
  switch: function(e) {
    const length = this.data.objectArray.length
    for (let i = 0; i < length; ++i) {
      const x = Math.floor(Math.random() * length)
      const y = Math.floor(Math.random() * length)
      const temp = this.data.objectArray[x]
      this.data.objectArray[x] = this.data.objectArray[y]
      this.data.objectArray[y] = temp
    }
    this.setData({
      objectArray: this.data.objectArray
    })
  },
  addToFront: function(e) {
    const length = this.data.objectArray.length
    this.data.objectArray = [{id: length, unique: 'unique_' + length}].concat(this.data.objectArray)
    this.setData({
      objectArray: this.data.objectArray
    })
  },
  addNumberToFront: function(e){
    this.data.numberArray = [ this.data.numberArray.length + 1 ].concat(this.data.numberArray)
    this.setData({
      numberArray: this.data.numberArray
    })
  }
})

注意:

當 wx:for 的值爲字符串時,會將字符串解析成字符串數組

<view wx:for="array">
  {{item}}
</view>

等同於

<view wx:for="{{['a','r','r','a','y']}}">
  {{item}}
</view>

注意:

花括號和引號之間如果有空格,將最終被解析成爲字符串

<view wx:for="{{[1,2,3]}} ">
  {{item}}
</view>

等同於

<view wx:for="{{[1,2,3] + ' '}}" >
  {{item}}
</view>

5.3 數據追加小技巧

 data: {
    numberArray: [1, 2, 3, 4]
  },
addNumberToFront: function(e){
    this.data.numberArray = [ this.data.numberArray.length + 1 ].concat(this.data.numberArray)
    this.setData({
      numberArray: this.data.numberArray
    })
  }

在這裏插入圖片描述

5.4 三點運算符

用於 template

//js代碼
<!--
item: {
  index: 0,
  msg: 'this is a template',
  time: '2016-06-18'
}
-->


//wxml代碼
<template name="msgItem">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>


<template is="msgItem" data="{{...item}}"/>

<!-- 輸出
0: this is a template Time: 2016-06-18
-->

6. detail 詳情頁

6.1 商品數據

大概就是這種格式

goodsDetail: {
	"basicInfo": {
		"pic": "/image/new.jpg",
		"name": "水果"
	},
	"properties": [{
			"name": "重量",
			"option": [{
					"name": "1kg",
					"active": true
				},
				{
					"name": "2kg",
					"active": false
				},
				{
					"name": "3kg",
					"active": false
				}
			]
		},
		{
			"name": "選項2",
			"option": [{
					"name": "1kg",
					"active": true
				},
				{
					"name": "2kg",
					"active": false
				}
			]
		}
	]
}

6.2 頁面隱藏

hidden 屬性

<view class="row-arrow" bindtap="bindGuiGeTap">
	選擇尺碼
</view>

<view class="show-popup" hidden="{{hideShopPopup}}" >
	emmm
<view/>
data: {
	hideShopPopup: true,
},

bindGuiGeTap: function () {
	this.setData({
		hideShopPopup: false
	})
},
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章