之前的文章(跳转链接)中,路径在离线打包后不可读取,所以想了两个办法来解决。
方法一(推荐):
加载时耗时较少,唯一的问题就是url参数长度有限制,但也不必担忧,因为文件的路径不会过长。
1、在getData.js文件中封装获取文件绝对路径的方法:
const filePath = function() {
return plus.io.convertLocalFileSystemURL("_doc/MY_DATA.json");
}
export default {
getdatas,
filePath
};
2、在调用web-view的vue界面中使用url传参的方式将文件绝对路径传给local.html文件。
<template>
<view><web-view :src="url"></web-view></view>
</template>
<script>
import getData from '@/common/getData.js';
export default {
data() {
return {
url: '/hybrid/html/local.html?data='
};
},
onLoad() {
//这里对要传入到webview中的参数进行encodeURIComponent编码否则中文乱码
this.url += encodeURIComponent(getData.filePath());
}
};
</script>
<style></style>
3、在local.html文件中处理传过来的参数。
//获取 uni-app 传来的值,即文件的绝对路径
var filePath = getQuery('data');
//取url中的参数值
function getQuery(name) {
// 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在)
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
let r = window.location.search.substr(1).match(reg);
console.log(r);
if (r != null) {
// 对参数值进行解码
return decodeURIComponent(r[2]);
}
return null;
}
方法二(也很好):
唯一的缺点就是加载plus有点耗时,比方法一多消耗3-5s的时间。
1、在local.html页面中直接使用。
// 扩展API加载完毕后调用onPlusReady回调函数
document.addEventListener( "plusready", onPlusReady, false );
// 扩展API加载完毕,现在可以正常调用扩展API
function onPlusReady(){
var url="_doc/MY_DATA.json";
var path=plus.io.convertLocalFileSystemURL(url);
//一定要写在这里,因为异步问题
if (mydata.length == 0) {
$.ajaxSettings.async = false; //把异步操作转化成同步操作,否则无法在函数外拿到请求值
$.getJSON(path, function(result) {
mydata= result.data;//虽然写入的时候要求转换成string,但是写入后的数据是原格式的
});
$.ajaxSettings.async = true; //执行完成后恢复成异步
}
}