问题:在使用uni-app开发微信小程序时,需要解析富文本中的a标签的href值,拿到下载地址,绑定事件调用下载方法,并支持图片预览。
解决方法:
使用uView的u-parse组件实现,代码如下:
<template>
<view style="padding: 20rpx;">
<u-parse :html="requestdata.content" @linkpress="navigate"></u-parse>
</view>
</template>
<script>
export default{
created() {
},
//我这里是个组件,data通过props传入
props:{
requestdata: {
type: Object,
default: ()=>{}
},
},
data(){
return{
}
},
methods:{
navigate(obj) {
this.download(obj.href);
},
download(href){
let url = href;
console.log(url)
uni.downloadFile({
url, //文件链接
success:({statusCode,tempFilePath})=>{
console.log(statusCode,tempFilePath)
//statusCode状态为200表示请求成功,tempFIlePath临时路径
if(statusCode==200){
//保存到本地
uni.saveFile({
tempFilePath,
success:(res)=>{
//res.savedFilePath文件的保存路径
//保存成功并打开文件
uni.openDocument({
filePath:res.savedFilePath,
showMenu: true, // 允许出现分享功能
success:(res)=>{
console.log('成功打开文档')
},
fail:(err)=>{
this.toast('打开失败')
}
})
},
fail:(err)=>{
this.toast('保存失败')
},
})
}else{
this.toast('未找到资源文件')
}
},
fail:(err)=>{
this.toast('下载失败')
}
})
},
toast(mes){
uni.showToast({
title: mes,
icon: 'none',
duration: 1500
})
}
}
}
</script>