移动端环境下Vue.js与iframe结合使用

前言

本文github地址可进行下载
需求:在vue中的超链接要在本页面展示,而浏览器的地址栏不会变化。这个前提我们今天主角就出来。
原理:就是在a标签的target属性指定到iframe的name的值。

一、iframe简介

iframe 元素会创建包含另外一个文档的内联框架(即行内框架)。W3C相关介绍

二、 vue-cli中用iframe

1. 使用vue脚手架生成一个带路由功能的项目。
2.在页面中引用iframe

首先,超链接的数据是通过接口返回的。刚开始返回按钮和iframe是不显示。只有点击a便签的时候在会在iframe显示网页内容
template中内容

<div class="go-back" v-show="goBackState" @click="goBack">回去</div>
<ul>
    <li v-for="item in webAddress">
       <a :href="item.link" target="showHere" @click="showIframe">{{item.name}}</a>
    </li>
</ul>
<iframe v-show="iframeState" id="show-iframe"  frameborder=0 name="showHere" scrolling=auto src=""></iframe>

script中内容

export default {
  name: 'hello',
  data () {
    return {
      iframeState:false,
      goBackState:false,
      webAddress: [
        {
            name:'router',
            link:'http://router.vuejs.org/'
        },
        {
          name:'vuex',
          link:'http://vuex.vuejs.org/'
        },
        {
          name:'iframeAPI',
          link:'https://msdn.microsoft.com/en-us/library/ms535258(v=vs.85).aspx'
        }
      ]
    }
  },
  mounted(){
    const oIframe = document.getElementById('show-iframe');
    const deviceWidth = document.documentElement.clientWidth;
    const deviceHeight = document.documentElement.clientHeight;
    oIframe.style.width = deviceWidth + 'px';
    oIframe.style.height = deviceHeight + 'px';
  },
  methods:{
    goBack(){
      console.log('回到主页');
      this.goBackState = false;
      this.iframeState = false;
    },
    showIframe(){
      console.log('显示iframe');
      this.goBackState = true;
      this.iframeState = true;
    }
  }
}

三、页面效果展示

**1. ** 页面展示包含超链接



**2. ** 在iframe中进行超链跳转


四、iframe问题总结

**1. **最近些项目遇到用iframe的地方,发现设置的固定高有时不能完全适应项目环境,不是高了就是不够高,在页面里看着很不爽。解决方案就是在钩子函数mounted中获取设备的宽和高并设置给iframe。
**2. **如果是初始没有a标签,那就需要事件委托来进行处理了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容