美文网首页
vue组件与html文件相互传参

vue组件与html文件相互传参

作者: 苏苡 | 来源:发表于2023-07-20 15:49 被阅读0次

    <iframe :src="src" ref="iframe" style="width:100%;height:100%" @click="vueSendMsgv-trigger></ iframe>

    <button @click="htmlFunClick">触发html方法</button>

     // 自定义方法传参准备

    directives: {

            trigger: {  

                         inserted (el, pinging) {

                                      el.click()

                         }

              } 

    },

    methods() {

          // 触发方法 传参给html文件

            vueSendMsg() {

                setTimeout(() =>{

                        const iframeWindow = this.$refs.iframe.contentWindow

                        iframeWindow.postMessage({

                                cmd: 'myVue',

                                 params: {

                                        id: this.$route.query.id

                                }

                        }, '*')

            }, 1000),

           htmlFunClick(){

                     this.$refs.iframe.contentWindow.clickfun()     // 触发html定义的clickfun方法

                    window['setThis'] = (message, data) => {  // 接受html传过来的参数

                            console.log(message, data)    //   console -----> '触发成功', '1234'

                     }

            }

    },

    <script>

      // 准备接受vue 传给的参数

        window.addEventListener("message", getVueData)

        function getVueData(event) {

                console.log(event.data)  // vue 传给的参数

        }

         function clickfun(event) { 

                console.log("html方法被触发啦!")

                window.parent['setThis']('触发成功', '1234')    // 传参给vue文件

        }

    </script>

    相关文章

      网友评论

          本文标题:vue组件与html文件相互传参

          本文链接:https://www.haomeiwen.com/subject/hdlzudtx.html