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

2017-06-24  本文已影响4778人  诺奕

前言

本文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标签,那就需要事件委托来进行处理了。

上一篇 下一篇

猜你喜欢

热点阅读