Javascript 如何在vue.js中使用iframe显示pdf

Javascript 如何在vue.js中使用iframe显示pdf,javascript,pdf,iframe,vue.js,vuejs2,Javascript,Pdf,Iframe,Vue.js,Vuejs2,我有一个vue.js webapp,我想在应用程序中的iframe中显示一个PDF,但它不采用资产文件夹中的路径。这是我的密码: <iframe :src="getPDFPath()" style="width: 100vw;height: 100%;border: none;"> Oops! an error has occurred. </iframe> 但这不起作用,并产生以下错误: 无法获取/assets/my.pdf 然而,{{getPDFPath()}的

我有一个vue.js webapp,我想在应用程序中的iframe中显示一个PDF,但它不采用
资产
文件夹中的路径。这是我的密码:

<iframe :src="getPDFPath()" style="width: 100vw;height: 100%;border: none;">
  Oops! an error has occurred.
</iframe>
但这不起作用,并产生以下错误:

无法获取/assets/my.pdf

然而,
{{getPDFPath()}
的结果是:
。/../assets/my.pdf

由于我正在使用webpack,我还尝试了以下内容,但也不起作用:

getPDFPath () {
  var files = require.context('../../assets/', false)
  return files('./my.pdf')
}
这给了我以下错误:

/src/assets/my.pdf

模块解析失败:>/Users/abc/work/codes/vue/src/assets/my.pdf 意外令牌(1:0)

您可能需要适当的加载程序来处理此文件类型

但是,正如我前面回答的那样,上面的代码适用于图像。

1模板

<iframe :src="pdfsrc" style="width: 100%;height: 300px; border: none;">
Oops! an error has occurred.
</iframe>

哎呀!发生了一个错误。
2脚本

<script>
export default {
  data: () => ({
    pdfsrc: null
  }),
  methods: {
    getPDFPath () {
      return axios
      .get('/sample-3pp.pdf', {
        responseType: "blob"
      })
      .then(response => {
        console.log("Success", response);
        const blob = new Blob([response.data]);
        const objectUrl = URL.createObjectURL(blob);
        this.pdfsrc = objectUrl;
      })
     .catch(console.error); //
    } 
    created() {
        this.getPDFPath();
    }
}
</script>

导出默认值{
数据:()=>({
pdfsrc:null
}),
方法:{
getPDFPath(){
返回轴
.get('/sample-3pp.pdf'{
响应类型:“blob”
})
。然后(响应=>{
console.log(“成功”,响应);
const blob=新blob([response.data]);
const objectUrl=URL.createObjectURL(blob);
this.pdfsrc=objectUrl;
})
.catch(控制台错误)//
} 
创建(){
这是一个.getPDFPath();
}
}

当您返回
'../assets/my.pdf'
字符串时发生了什么?@SLYcee不,我想“()”是needed@AmreshVenugopal我在问题中添加了错误。因此您返回
'../../assets/my.pdf'
,但错误显示为
'/assets/my.pdf'
?如果执行{{{getPDFPath()},结果是否相同就在
上方?是否要对pdf进行简单引用?是否可以通过http直接访问?是否可以使用绝对路径?
<script>
export default {
  data: () => ({
    pdfsrc: null
  }),
  methods: {
    getPDFPath () {
      return axios
      .get('/sample-3pp.pdf', {
        responseType: "blob"
      })
      .then(response => {
        console.log("Success", response);
        const blob = new Blob([response.data]);
        const objectUrl = URL.createObjectURL(blob);
        this.pdfsrc = objectUrl;
      })
     .catch(console.error); //
    } 
    created() {
        this.getPDFPath();
    }
}
</script>