解决IE浏览器不识别location.origin 的问题

IE 不能识别location.origin的问题。。。

if (window["context"] == undefined) {
        if (!window.location.origin) {
            window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
        }
        window["context"] = location.origin + "/V6.0";
    }
在 Vue 中,`${window.location.origin}` 是 JavaScript 模板字符串的语法,结合 `window.location.origin` 属性来获取当前页面的基础 URL。`window.location.origin` 返回当前页面的协议、主机名和端口号组成的完整基础 URL(若端口是默认的 80 或 443 则省略)[^1]。 ### 使用方法 #### 在模板中使用 在 Vue 组件的模板部分,可以使用计算属性或者直接在插值表达式中引用 `window.location.origin`。 ```vue <template> <div> <!-- 直接使用 --> <p>当前页面的基础 URL 是:{{ window.location.origin }}</p> <!-- 使用计算属性 --> <p>当前页面的基础 URL(通过计算属性)是:{{ baseUrl }}</p> </div> </template> <script> export default { computed: { baseUrl() { return window.location.origin; } } }; </script> ``` #### 在方法中使用 在 Vue 组件的方法中也可以使用 `window.location.origin` 来构建 URL。 ```vue <template> <div> <button @click="goToApi">访问 API</button> </div> </template> <script> export default { methods: { goToApi() { const apiUrl = `${window.location.origin}/api/data`; // 这里可以发起 API 请求,例如使用 axios console.log('即将访问的 API URL 是:', apiUrl); } } }; </script> ``` ### 使用场景 #### 构建绝对路径 在构建指向同一域名下其他资源的绝对路径时,可以使用 `window.location.origin`。比如在开发一个多页面应用时,要从一个页面跳转到另一个页面,可以使用如下方式: ```vue <template> <div> <a :href="`${window.location.origin}/another-page`">跳转到另一个页面</a> </div> </template> ``` #### 发起 API 请求 在前后端分离的项目中,前端需要向后端 API 发送请求。使用 `window.location.origin` 可以方便地构建 API 请求的基础 URL,确保请求发送到正确的服务器。 ```vue <script> import axios from 'axios'; export default { methods: { fetchData() { const apiUrl = `${window.location.origin}/api/data`; axios.get(apiUrl) .then(response => { console.log('获取到的数据:', response.data); }) .catch(error => { console.error('请求出错:', error); }); } } }; </script> ``` #### 跨域资源加载 当需要加载同一域名下的其他资源(如图片、脚本等)时,使用 `window.location.origin` 可以确保资源加载的正确性。 ```vue <template> <div> <img :src="`${window.location.origin}/images/logo.png`" alt="Logo"> </div> </template> ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值