element-ui vue2 iframe 嵌入外链新解

效果如图

实现原理

  • 在路由中通过  props 传值

  {
    path: '/iframe',
    component: Layout,
    meta: { title: '小助手', icon: 'example' },
    children: [
      {
        path: 'chatglm',
        name: 'chatglm',
        props: {  name: 'chatglm',url: 'https://chatglm.cn' },
        component: () => import('@/views/iframe/common'),
        meta: { title: 'ai-智普清言', icon: 'table' }
      },
]
  • 组件中获取数据  this.$props.url

<template>
    <div class="iframe-container">
      <iframe :src="src" scrolling="auto" frameborder="0" class="frame" :onload="onloaded()">
      </iframe>
    </div>
  </template>
  
  <script>
  export default {

    props: ['url']  ,

    data() {
      return {
        src: this.$props.url,
        loading: null
      };
    },
    methods: {
      // 获取路径
      resetSrc: function(url) {
        this.src = url
        this.load()
      },
      load: function() {
        this.loading = this.$loading({  
          lock: true,
          text: "loading...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.5)",
          // fullscreen: false,
          target: document.querySelector("#main-container ")
        })
      },
      onloaded: function() {
        if(this.loading) {
          this.loading.close()
        }
      }
    },
    mounted() {
      this.resetSrc(this.$props.url);
    },
    watch: {
      $route: {
        handler: function(val, oldVal) {
          // 如果是跳转到嵌套页面,切换iframe的url
          this.resetSrc(this.$props.url);
        }
      }
    }
  };
  </script>
  
  <style lang="scss">
  .iframe-container {
    position: absolute;
    top: 0px;
    left: 0px;
    right: 0px;;
    bottom: 0px;
    .frame {
      width: 100%;
      height: 100%;
    }
  }
  </style>
  

参考

src/views/IFrame/IFrame.vue · 朝雨忆轻尘(Louis)/kitty-ui - Gitee.com

Vue 路由组件传参的 8 种方式 - 掘金

猜你喜欢

转载自blog.csdn.net/qq_34068440/article/details/134084834