小程序基礎開發(四):template模板應用(1)——帶搜索歷史的搜索欄

一,template模板

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

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

{{index}}: {{msg}} Time: {{time}} 使用模板 使用 is 屬性,聲明需要的使用的模板,然後將模板所需要的 data 傳入,如: Page({ data: { item: { index: 0, msg: 'this is a template', time: '2016-09-15' } } }) is 屬性可以使用 Mustache 語法,來動態決定具體需要渲染哪個模板: odd even 模板的作用域 模板擁有自己的作用域,只能使用 data 傳入的數據以及模板定義文件中定義的 模塊。

二,帶搜索歷史的搜索欄

在template目錄裏寫好模板的wxml

<!--模塊1-搜索欄--->
<template name="SearchView">
  <view class="weui-search-bar">
    <view class="weui-search-bar__form">
      <view class="weui-search-bar__box">
        <icon class="weui-icon-search_in-box" type="search" size="14"></icon>
        <input type="text" class="weui-search-bar__input"  disabled='true' placeholder="搜索入口" bindtap="wxSearchTab"/>
      </view>
    </view>
  </view> 
  <view>{{searchValue}}</view>
</template>

引用wxSearchView組件
js

/***
 * // 定義數據格式
 * "wxSearchData":{
 *  configconfig:{
 *    style: "wxSearchNormal"
 *  },
 *  view:{
 *    hidden: true,
 *    searchbarHeght: 20
 *  }
 *  hotKeys:[],//自定義熱門搜索
 *  his:[]//歷史搜索關鍵字
 *  value
 * }
 */

// 提示集合
var __tipKeys = [];
// 搜索回調函數 
var __searchFunction = null;
// 返回函數 
var __goBackFunction = null;
// 應用變量
var __that = null;

// 初始化函數
function init(that, hotKeys, tipKeys, searchFunction, goBackFunction) {

  __that = that;
  __tipKeys = tipKeys;
  __searchFunction = searchFunction;
  __goBackFunction = goBackFunction;

  var temData = {};
  var barHeight = 43;
  var view = {
    barHeight: barHeight
  }
  temData.hotKeys = hotKeys;

  wx.getSystemInfo({
    success: function (res) {
      var wHeight = res.windowHeight;
      view.seachHeight = wHeight - barHeight;
      temData.view = view;
      __that.setData({
        wxSearchData: temData
      });
    }
  });

  getHisKeys(__that);
}

// 搜索框輸入時候操作
function wxSearchInput(e) {
  var inputValue = e.detail.value;
  // 頁面數據
  var temData = __that.data.wxSearchData;
  // 尋找提示值 
  var tipKeys = [];
  if (inputValue && inputValue.length > 0) {
    for (var i = 0; i < __tipKeys.length; i++) {
      var mindKey = __tipKeys[i];
      // 包含字符串
      if (mindKey.indexOf(inputValue) != -1) {
        tipKeys.push(mindKey);
      }
    }
  }
  // 更新數據
  temData.value = inputValue;
  temData.tipKeys = tipKeys;
  // 更新視圖
  __that.setData({
    wxSearchData: temData
  });
}

// 清空輸入
function wxSearchClear() {
  // 頁面數據
  var temData = __that.data.wxSearchData;
  // 更新數據
  temData.value = "";
  temData.tipKeys = [];
  // 更新視圖
  __that.setData({
    wxSearchData: temData
  });
}

// 點擊提示或者關鍵字、歷史記錄時的操作
function wxSearchKeyTap(e) {
  search(e.target.dataset.key);
}

// 確任或者回車
function wxSearchConfirm(e) {
  var key = e.target.dataset.key;
  if(key=='back'){
    __goBackFunction();
  }else{
    search(__that.data.wxSearchData.value);
  }
}

function search(inputValue) {
  if (inputValue && inputValue.length > 0) {
    // 添加歷史記錄
    wxSearchAddHisKey(inputValue);
    // 更新
    var temData = __that.data.wxSearchData;
    temData.value = inputValue;
    __that.setData({
      wxSearchData: temData
    });
    // 回調搜索
    __searchFunction(inputValue);
  }
}

// 讀取緩存
function getHisKeys() {
  var value = [];
  try {
    value = wx.getStorageSync('wxSearchHisKeys')
    if (value) {
      // Do something with return value
      var temData = __that.data.wxSearchData;
      temData.his = value;
      __that.setData({
        wxSearchData: temData
      });
    }
  } catch (e) {
    // Do something when catch error
  }
}

// 添加緩存
function wxSearchAddHisKey(inputValue) {
  if (!inputValue || inputValue.length == 0) {
    return;
  }
  var value = wx.getStorageSync('wxSearchHisKeys');
  if (value) {
    if (value.indexOf(inputValue) < 0) {
      value.unshift(inputValue);
    }
    wx.setStorage({
      key: "wxSearchHisKeys",
      data: value,
      success: function () {
        getHisKeys(__that);
      }
    })
  } else {
    value = [];
    value.push(inputValue);
    wx.setStorage({
      key: "wxSearchHisKeys",
      data: value,
      success: function () {
        getHisKeys(__that);
      }
    })
  }
}

// 刪除緩存
function wxSearchDeleteAll() {
  wx.removeStorage({
    key: 'wxSearchHisKeys',
    success: function (res) {
      var value = [];
      var temData = __that.data.wxSearchData;
      temData.his = value;
      __that.setData({
        wxSearchData: temData
      });
    }
  })
}

// 導出接口
module.exports = {
  init: init, //初始化函數
  wxSearchInput: wxSearchInput,// 輸入變化時的操作
  wxSearchKeyTap: wxSearchKeyTap, // 點擊提示或者關鍵字、歷史記錄時的操作
  wxSearchDeleteAll: wxSearchDeleteAll, // 刪除所有的歷史記錄
  wxSearchConfirm: wxSearchConfirm, // 搜索函數
  wxSearchClear: wxSearchClear,  // 清空函數
}

wxml

<cu-custom bgColor="bg-gradual-{{Theme}}">
  <view slot="content">搜索</view>
</cu-custom>
<view class="weui-search-bar">
   <view class="weui-search-bar__form">
    <view class="weui-search-bar__box">
      <icon class="weui-icon-search_in-box" type="search" size="14"></icon>
      <input type="text" class="weui-search-bar__input" placeholder="請輸入查詢內容" value="{{wxSearchData.value}}" bindinput="wxSearchInput" bindconfirm="wxSearchConfirm" />
      <view class="weui-icon-clear" wx:if="{{wxSearchData.value.length > 0}}" bindtap="wxSearchClear">
        <icon type="clear" size="14"></icon>
      </view>
    </view>
  </view>
    <view class="weui-search-bar__cancel-btn" bindtap="wxSearchConfirm">
         <text class='text-{{Theme}}' wx:if="{{wxSearchData.value.length>0}}" data-key='search'>搜索</text>
         <text class='text-{{Theme}}' wx:else data-key='back'>返回</text>
    </view>
</view>

<view class="wxSearch">

  <view class="wxSearchInner">
    <!-- 搜索提示部分 -->
    <view class="wxSearchMindKey">
      <view class="wxSearchMindKeyList">
        <block wx:for="{{wxSearchData.tipKeys}}" wx:key="*this">
          <view class="wxSearchMindKeyItem" bindtap="wxSearchKeyTap" data-key="{{item}}">{{item}}</view>
        </block>
      </view>
    </view>

    <view wx:if="{{wxSearchData.his[0]}}" class="wxSearchHistory" style="display:{{wxSearchData.value.length>0 ? 'none':'block'}}">
      <view class="wxSearchHistoryItem">
        <text class="wxSearchHistoryItemTitle">搜索記錄</text>
        <!--text class="wxSearchHistoryItemDel" bindtap="wxSearchDeleteAll">刪除</text-->
        <icon type="clear" bindtap="wxSearchDeleteAll" size="18" />
      </view>
      <view class="wxSearchKeyList">
        <block wx:for="{{wxSearchData.his}}" wx:key="*this">
          <view class="wxSearchKeyItem" bindtap="wxSearchKeyTap" data-key="{{item}}">{{item}}</view>
        </block>
      </view>
    </view>

    <view class="wxSearchKey" style="display:{{wxSearchData.value.length>0 ? 'none':'block'}}">
      <text wx:if="{{wxSearchData.hotKeys[0]}}" class="wxSearchTitle">熱門搜索</text>
      <view class="wxSearchKeyList">
        <block wx:for="{{wxSearchData.hotKeys}}" wx:key="*this">
          <view class="wxSearchKeyItem" bindtap="wxSearchKeyTap" data-key="{{item}}">{{item}}</view>
        </block>
      </view>
    </view>
  </view>
</view>

css

/** 整個區域 */
.wxSearch{
  width: 100%;
  height: 100%;
  border-top: 1px #eee solid;
  background-color: rgba(200, 200, 200, 0.1);
  z-index: 9999;
}

/** 搜索框下面的提示區域 */
.wxSearchInner{
  background-color: #fff;
}

/** 搜索熱點標題 */
.wxSearchTitle{
  display: block;
  padding: 10px 5px 5px 10px;
  font-size: 13px;
  text-align: left;
}

/** 提示樣式 */
.wxSearchMindKeyItem{
  padding: 10px 5px 10px 15px;
  margin-left: 10px;
  border-bottom: 1px solid #eee;
  display: flex;
  font-size: 13px;
}

/** 標籤樣式 */
.wxSearchKeyList{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  border-bottom: 1px solid #eee;
}

/** 標籤樣式 */
.wxSearchKeyItem{
  flex: 0 0 18%;
  font-size: 13px;
  text-align: center;
  border: 1px solid #eee;
  margin: 5px;
  padding: 4px 5px 4px 5px;
  border-radius: 0px;
  background-color: rgba(200, 200, 200, 0.1);
}

/** 搜索記錄標題欄 */
.wxSearchHistoryItem{
  padding-left: 10px;
  padding-top: 10px;
  padding-right: 5px;
  padding-bottom: 5px;
  display: flex;
}

/** 搜索記錄標題 */
.wxSearchHistoryItemTitle{
  flex: 8;
  font-size: 13px;
}

/** 搜索記錄刪除按鈕 */
.wxSearchHistoryItemDel{
  flex: 1;
  font-size: 13px;
  text-align: center;
  padding-top:2px;
  padding-bottom: 2px;
  border: 1px solid #eee;
  border-radius: 2px;
}

/** ---------------------- 以下是搜索框的 we-ui 樣式--------------------------------*/

/*!
 * WeUI v1.1.1 (https://github.com/weui/weui-wxss)
 * Copyright 2017 Tencent, Inc.
 * Licensed under the MIT license
 */

.weui-search-bar {
  position: relative;
  padding: 8px 10px;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  box-sizing: border-box;
  background-color: #efeff4;
  border-top: 1rpx solid #d7d6dc;
  border-bottom: 1rpx solid #d7d6dc;
}

.weui-icon-search {
  margin-right: 8px;
  font-size: inherit;
}

.weui-icon-search_in-box {
  position: absolute;
  left: 10px;
  top: 7px;
}

.weui-search-bar__text {
  display: inline-block;
  font-size: 14px;
  vertical-align: middle;
}

.weui-search-bar__form {
  position: relative;
  -webkit-box-flex: 1;
  -webkit-flex: auto;
  flex: auto;
  border-radius: 5px;
  background: #fff;
  border: 1rpx solid #e6e6ea;
}

.weui-search-bar__box {
  position: relative;
  padding-left: 30px;
  padding-right: 30px;
  width: 100%;
  box-sizing: border-box;
  z-index: 1;
}

.weui-search-bar__input {
  height: 28px;
  line-height: 28px;
  font-size: 14px;
}

.weui-icon-clear {
  position: absolute;
  top: 0;
  right: 0;
  padding: 7px 8px;
  font-size: 0;
}

.weui-search-bar__label {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 2;
  border-radius: 3px;
  text-align: center;
  color: #9b9b9b;
  background: #fff;
  line-height: 28px;
}

.weui-search-bar__cancel-btn {
  margin-left: 10px;
  line-height: 28px;
  color: #09bb07;
  white-space: nowrap;
}

創建一個搜索
js

// pages/search/search.js
var WxSearch = require('../../../../wxSearchView/wxSearchView.js');//搜索組件JS
const app = getApp();
let gocityarr = [{
  "id": "661",
  "name": "廣州"
},
{
  "id": "664",
  "name": "深圳"
},
{
  "id": "668",
  "name": "珠海"
},
{
  "id": "669",
  "name": "肇慶"
}];
let gocity_id = gocityarr['0'].id;
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    Theme: app.globalData.Theme,
  },

  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function (options) {
    var that = this;
    WxSearch.init(
      that,  // 本頁面一個引用
      [], // 熱點搜索()推薦,[]表示不使用
      [],// 搜索匹配,[]表示不使用
      that.mySearchFunction, // 提供一個搜索回調函數
      that.myGobackFunction //提供一個返回回調函數
    );

  },

  // 轉發函數,固定部分
  wxSearchInput: WxSearch.wxSearchInput,  // 輸入變化時的操作
  wxSearchKeyTap: WxSearch.wxSearchKeyTap,  // 點擊提示或者關鍵字、歷史記錄時的操作
  wxSearchDeleteAll: WxSearch.wxSearchDeleteAll, // 刪除所有的歷史記錄
  wxSearchConfirm: WxSearch.wxSearchConfirm,  // 搜索函數
  wxSearchClear: WxSearch.wxSearchClear,  // 清空函數

  // 搜索回調函數  
  mySearchFunction: function (value) {
    // do your job here
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];   //當前頁面
    var prevPage = pages[pages.length - 2];  //上一個頁面

    //直接調用上一個頁面的方法,把數據存到上一個頁面中去
    prevPage.searchlist(
      value
    )
    // 跳轉
    wx.navigateBack({
      delta: 1,//返回上一層(delta=層數)
    })
  },

  // 返回回調函數
  myGobackFunction: function () {
    wx.navigateBack({
      delta: 1,//返回上一層(delta=層數)
    })
    //console.log('搜索OK');
  },

  /**
   * 生命週期函數--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命週期函數--監聽頁面顯示
   */
  onShow: function () {

  },

  /**
   * 生命週期函數--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命週期函數--監聽頁面卸載
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函數--監聽用戶下拉動作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函數
   */
  onReachBottom: function () {

  },

  /**
   * 用戶點擊右上角分享
   */
  onShareAppMessage: function () {

  }
})

wxml

<include src="../../../../wxSearchView/wxSearchView.wxml" />

css

@import "../../../../wxSearchView/wxSearchView.wxss";

最後在需要添加搜索欄的頁面,引用模板即可
wxml

<import src='../../../../template/template.wxml'/>
<template is='SearchView'></template>
@import "../../../../wxSearchView/wxSearchView.wxss";
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章