本文实例为大家分享了微信小程序实现侧边栏二级联动的具体代码,供大家参考,具体内容如下
实现效果如下
实现步骤
样式布局(.wxml文件)
<scroll-view scroll-y="{{true}}"
style="height:{{height}}px;"
class="nav-right-menu">
<!-- 一级菜单 -->
<view class="nav-left-menu-list"
wx:for="{{Menu}}"
wx:for-index="idMenu"
wx:key="id">
<view data-index="{{idMenu}}"
class="nav-left-menu-text"
bindtap="showmenu2"
data-len="{{item.childLen}}">
<text>{{item.txt}}</text>
</view>
<!-- 二级菜单 -->
<view class="nav-left-secondmenu"
style="{{menuindex == idMenu ? menustyle : field}}">
<view class='nav-left-secondmenu-list'
wx:for="{{item.twoMenu}}"
wx:for-item="twoMenu"
wx:key="id"
bindtap="dosub"
data-url="{{twoMenu.menupath}}">
<text class='nav-left-Secondmenu-text'>{{twoMenu.name}}</text>
</view>
</view>
</view>
</scroll-view>
js文件
// pages/home/index.js
var app = getApp();
var systeminfo = null;
var currentMenuIndex = -1;
Page({
/**
* 页面的初始数据
*/
data: {
height: 0,
Menu:[]
},
showmenu2: function (event) {//显示2级菜单
var currentindex = event.currentTarget.dataset.index;
var len = event.currentTarget.dataset.len;
if (currentindex == currentMenuIndex) {
currentMenuIndex = -1;
len = 0;
}
else {
currentMenuIndex = currentindex;
len = len * 40;
}
this.setData({
menuindex: currentMenuIndex,
menustyle: "height:" + len + "px;transition:height 0.24s"
})
},
showmenu: function (event) {//显示一级菜单
this.setData({
showmask: true,
toolclass: "showmenu",
isscroll: false
})
},
hidemenu: function () {
this.setData({
showmask: false,
toolclass: "hidemenu",
isscroll: true
})
},
dosub: function (e) {
var path = e.currentTarget.dataset.url;
var obj = this;
wx.navigateTo({
url: path,
success: function (e) {
obj.setData({
isscroll: true,
showmask: false,
toolclass: "hidemenu"
})
}
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this;
var menujson = require("../../utils/side.js");
let side = menujson.getside();
console.log(side)
that.setData({
Menu: side
})
}
})
数据文件(side.js)
var side = [
{
"txt": "女装",
"id": "1",
"childLen": 3,
"twoMenu": [
{
"id": "3",
"name": "连衣裙",
"menupath": ""
},
{
"id": "4",
"name": "雪纺衬衣/T恤",
"menupath": ""
},
{
"id": "5",
"name": "套装",
"menupath": ""
}
]
},
{
"txt": "男装",
"id": "2",
"childLen": 4,
"twoMenu": [
{
"id": "6",
"name": "衬衣",
"menupath": ""
},
{
"id": "7",
"name": "T恤",
"menupath": ""
}
]
}
]
const getside = () => {
return side;
}
module.exports = {
getside: getside
}
最后页面显示出来了,也可以将side文件写入data里面,此处只是将文件写入外部,进行模块的导入,两种方法都可以。