使用 Vue.js 自动检测链接有效性并显示结果

以下代码示例展示了如何在 Vue.js 项目中自动检测链接有效性,并在按钮位置及时显示检测结果,直到页面关闭。

var icydm_pancheck = new Vue({
    el:'.icydm-pancheck',
    data:{
        data_text:'',
        data:'',
    },
    mounted(){
        if(window.location.pathname.indexOf('/post/') !== -1){
            this.checkPan();
            this.timer = setInterval(() => {
                this.checkPan();
            }, 30000);
        }
    },
    beforeDestroy() {
        clearInterval(this.timer);
    },
    methods:{
        checkPan(){
            if(!this.$refs.pancheck)return;
            let post_id = this.$refs.pancheck.getAttribute('data-id');
            this.$https.post(b2_global.site_info.admin_ajax,'id='+post_id+'&action=icydm_pancheck').then(res=>{
                this.data=res.data;
                if(this.data){
                    Qmsg['success'](this.data,{html:true}); 
                }else{
                    Qmsg['success']('正在检查中,请稍后点击...', {html:true}); 
                }
            });
        },
        pancheck(){
            this.checkPan();
        }
    }
});

代码解释

  1. mounted 钩子函数:当 Vue 实例创建完成后,会自动执行 mounted 钩子函数。

    • 代码中使用 window.location.pathname.indexOf('/post/') !== -1 判断当前页面是否为文章页。
    • 如果是文章页,则调用 checkPan 函数进行链接有效性检测,并使用 setInterval 函数每 30 秒执行一次 checkPan 函数,确保链接有效性持续检测。
  2. beforeDestroy 钩子函数:当 Vue 实例销毁前,会自动执行 beforeDestroy 钩子函数。

    • 使用 clearInterval 函数清除 setInterval 函数设置的定时器,避免页面关闭后还继续执行检测链接有效性的代码。
  3. checkPan 函数:该函数负责向服务器发送请求,获取链接有效性信息。

    • 获取按钮的 data-id 属性值,并发送 POST 请求到服务器。
    • 根据服务器返回的结果,使用 Qmsg['success'] 函数显示相应的提示信息。

总结

通过上述代码示例,可以在文章页内自动检测链接有效性,并在按钮位置及时显示检测结果,直到页面关闭。这可以帮助用户快速了解链接的有效性,提高用户体验。

注意:

  • 代码中使用了 Qmsg 对象,请确保 Qmsg 对象已定义并在项目中可用。
  • 代码中使用了 $https 对象,请确保 $https 对象已定义并在项目中可用。
  • 代码中的 b2_global.site_info.admin_ajax 是服务器端 AJAX 接口的地址,请根据实际情况进行修改。
  • 调整代码中 setInterval 函数的时间间隔,根据需要调整检测频率。
Vue.js 自动检测链接有效性并及时显示在按钮位置

原文地址: https://www.cveoy.top/t/topic/oUnN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录