在vue中嵌入iframe页面

[Talk is cheap. Show me the code]

不想看理论知识请直接移步最后代码示例。

一、嵌入iframe页面业务场景

项目是一个物流运营平台的管理系统,系统中对接了第三方的客服系统。因此这里需要在自己的页面中嵌入三方客服聊天的页面(这里对接了智齿)。ps:别问我为什么不自己写一个聊天的功能,问就是不知道。

二、iframe是什么

ifram标签规定了一个内联框架,让我们有可能在当前的HTML文档中嵌入另外一个文档,目前所有的主流浏览器都支持iframe标签,当然为了以防万一你可以在iframe标签中写入提示文本,以提示用户当前使用的浏览器不支持iframe。

<iframe src="http://www.baidu.com">
    IE:你们都看我干吗,我现在也是支持的
</iframe></
Vue 框架中使用 `<iframe>` 标签嵌入外部页面是一种常见需求,尤其在需要展示第三方内容或集成外部服务时。实现这一功能可以通过直接在组件的模板中使用原生 HTML 的 `<iframe>` 标签,也可以封装一个可复用的 iframe 组件来提升代码的维护性和扩展性。 ### 基本实现方式 在 Vue 中可以直接使用 HTML 的 `<iframe>` 标签,并通过 `:src` 动态绑定 URL: ```vue <template> <div> <iframe :src="iframeUrl" width="100%" height="600px" frameborder="0"></iframe> </div> </template> <script> export default { data() { return { iframeUrl: 'https://www.example.com' }; } }; </script> ``` 这种方式简单直观,适用于不需要额外封装逻辑的场景。 ### 封装可复用的 iframe 组件 为了增强组件的可维护性,可以将 `<iframe>` 封装为一个独立的 Vue 组件。以下是一个封装后的 `IframeComponent.vue` 示例: ```vue <!-- IframeComponent.vue --> <template> <iframe :src="url" :width="width" :height="height" frameborder="0" style="border: none;"></iframe> </template> <script> export default { props: { url: { type: String, required: true }, width: { type: String, default: '100%' }, height: { type: String, default: '600px' } } }; </script> ``` 在父组件中使用该封装组件: ```vue <template> <div> <IframeComponent :url="iframeUrl" width="100%" height="600px" /> </div> </template> <script> import IframeComponent from './components/IframeComponent.vue'; export default { components: { IframeComponent }, data() { return { iframeUrl: 'https://www.example.com' }; } }; </script> ``` ### 动态修改 iframe 的 URL 如果需要动态更新 `<iframe>` 的 `src` 属性,可以在数据模型中定义 `iframeUrl` 并通过 `v-model` 或其他事件机制进行更新: ```vue <template> <div> <input v-model="iframeUrl" placeholder="输入新的 URL" /> <IframeComponent :url="iframeUrl" width="100%" height="600px" /> </div> </template> <script> import IframeComponent from './components/IframeComponent.vue'; export default { components: { IframeComponent }, data() { return { iframeUrl: 'https://www.example.com' }; } }; </script> ``` 这样用户可以通过输入框更改 iframe 显示的内容,同时保持良好的组件化结构和可维护性[^1]。 ---
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值