1 let requireModule = require.context( 2 "文件路徑位置", 3 false, 4 /.jpg$/ //文件后綴名 5 ); 6 let imagesNameArr = []; 7 //獲取文件夾下面的所有滿足需求的文件 8 for (let i = 0; i < requireModule.keys().length; i++) { 9 imagesNameArr.push(requireModule.keys()[i].substr(2, requireModule.keys()[i].length)); 10 } 11 //從上面的數(shù)組中隨機(jī)篩選 12 function getRandomArrayElements(arr, count) { 13 let shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index; 14 while (i-- > min) { 15 index = Math.floor((i + 1) * Math.random()); 16 temp = shuffled[index]; 17 shuffled[index] = shuffled[i]; 18 shuffled[i] = temp; 19 } 20 return shuffled.slice(min); 21 } 22 //獲取到隨機(jī)的文件并補(bǔ)全路徑在頁面上顯示 23 let imgLinkArray = getRandomArrayElements(imagesNameArr,4) 24 for(let i=0;i<imgLinkArray.length;i++){ 25 let img = require("文件存放的路徑" + imgLinkArray[i]) 26 this.phonePic.push(img) 27 }
?
本文摘自 :https://www.cnblogs.com/