1. 程式人生 > 實用技巧 >uniapp中app端頁面中有多個圖片需要預覽,且需要左右滑動(即時通訊中的聊天)

uniapp中app端頁面中有多個圖片需要預覽,且需要左右滑動(即時通訊中的聊天)

1.點選圖片時,先獲取所有的訊息,將帶有圖片的訊息儲存為一個圖片陣列。

// arr是新圖片陣列    this.msglist是所有訊息的陣列
let arr = []
this.msglist.forEach((item,index) => {
    // 有img是圖片訊息
    if(item.img){
        arr.push(item.img)
    }
})

2.獲取當前圖片在 預覽圖片陣列 中的索引(e點選圖片的資料)

let index = arr.findIndex(value => value == e.img)

3.呼叫uniapp預覽圖片的api

uni.previewImage({
    current: index,
    urls: arr,
    longPressActions: {
        itemList: ['傳送給朋友', '儲存圖片', '收藏'],
        success: function(data) {
            console.log('選中了第' + (data.tapIndex + 1) + '個按鈕,第' +                 
            (data.index + 1) + '張圖片');
        },
        fail: 
function(err) { console.log(err.errMsg); } } });

完整程式碼:

// 預覽圖片
            previewImgClick(e){
                console.log(e);
                // 預覽圖片的陣列
                let arr = []
                this.msglist.forEach((item,index) => {
                    if(item.img){
                        arr.push(item.img)
                    }
                })
                
// 當前圖片在 預覽圖片陣列中的索引 let index = arr.findIndex(value => value == e.img) console.log(index); console.log(arr); uni.previewImage({ current: index, urls: arr, longPressActions: { itemList: ['傳送給朋友', '儲存圖片', '收藏'], success: function(data) { console.log('選中了第' + (data.tapIndex + 1) + '個按鈕,第' + (data.index + 1) + '張圖片'); }, fail: function(err) { console.log(err.errMsg); } } }); },