JavaScript不使用vue实现三个不同页面中的input跨页面响应式

36 篇文章 8 订阅
4 篇文章 2 订阅
本文探讨了使用Vue实现响应式的同时,如何通过iframe和localStorage技术实现在不同页面间的数据共享。通过iframe尝试嵌套页面,并利用location.href处理参数传递;localStorage则展示了其在跨页面响应中的优势,包括存储和监听事件的应用。
摘要由CSDN通过智能技术生成

看到这个题目还是有点迷惑的,除了用vue可以实现响应式 还能怎么实现

先说说我的思路 你也可以评论说出你的思路 动手试试

一、iframe  

实现效果

 

 

iframe 是我第一个思路 可能的确不知道怎么才能三个页面一起响应

可不可以把其他两个页面用iframe嵌入进来呢 通过src属性用?的形式进行拼接呢,所以尝试了一下 过程还是稍微繁琐的 

主页面

每次触发input事件 把value的值利用路由拼接的格式传给其他iframe页面标签

    <h3>我是主页面</h3>
    <input type="text" name="" id="" style="display: flex;">
    <iframe src="./iframe1.html" frameborder="0" style="display: none;"></iframe>
    <iframe src="./iframe2.html" frameborder="0" style="display: none;"></iframe>
    <script>
        let input = document.querySelector('input')
        let iframe1 = document.querySelectorAll('iframe')[0]
        let iframe2 = document.querySelectorAll('iframe')[1]
        input.oninput=()=>{
            iframe1.src='./iframe1.html?id='+input.value
            iframe2.src='./iframe2.html?id='+input.value
        }
    </script>

子页面

另一个页面和当前页面一样 所以有一份就可以了

 通过获取索引的最后一个= 拿到当前值,第一次页面是空的所以拿到的索引为0,0意味着下一步截取值的时候截取到的是整个路径,所以我又对它取了长度 如果为0的时候 就从长度开始 什么页截取不到

<body>
    <h3>我是第一个页面</h3>
    <input type="text" name="" id="">
    <script>

       let dataIndex = window.location.href.indexOf('=')+1
       let dataLength = window.location.href.length
       let data = window.location.href.slice(dataIndex?dataIndex:dataLength)
       let input = document.querySelector('input')
       input.value=data
    </script>
</body>

二、localstorage

一开始想看看localstorage 在一个页面上添加一个值 其他页面会不会有,结果是不但有 还是响应式的 只要你修改了当前localstorage的值,其他页面的localstorage也会进行响应,注意哈 只有localstorage是可以多个页面进行共享的(iframe中的session也可以),但不能跨浏览器之间的共享

效果图 这个效果还是比较帅的

 (1)主页面

<body>
    <h3>我是主页面</h3>
    <input type="text" name="" id="">
    <script> 
       let input = document.querySelector('input')
       input.oninput=()=>{
           localStorage.setItem('str',input.value)
       }
    </script>
</body>

 (2)子页面

注意哈 storage事件是我们平常没有用到的 

WindowEventHandlers.onstorage: 该事件不在导致数据变化的当前页面触发(如果浏览器同时打开一个域名下面的多个页面,当其中的一个页面改变 sessionStorage 或 localStorage 的数据时,其他所有页面的  storage  事件会被触发,而原始页面并不触发 storage 事件

<body>
    <h3>我是子页面1</h3>
    <input type="text" name="" id="">
    <script>
       let input = document.querySelector('input')
       window.addEventListener('storage',(e)=>{
           input.value=e.newValue
       })
    </script>
</body>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值