Vue——获取后端json数据中的URL并通过按钮跳转到此URL

获取的json数据

{“status”:"success","data":"https://www.baidu.com/"}

vue & axios 处理后端返回数据

index.vue

<template>
  <div class="container">
    <p>{
   
   {msg.data}}</p>

    <button 
        type="submit" 
        class="btn btn-primary"
        @click="jumptonewtab">点击 jump_to_new_tab
    </button>

    <p style="margin-top:10px"><a href="ping" target="_blank">点击</a></p>
    
    <button class="btn btn-primary" @click="jumptoself">点击 jump_to_self</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'vnctest',
  data() {
    return {
      msg: '...',
    };
  },
  methods: {
    getMessage() {
      const path = 'http://127.0.0.1:5000/';
      axios.get(path)
        .then((res) => {
          this.msg = res.data;
        })
        .catch((error) => {
          console.error(error);
        });
    },
    jumptonewtab(){
        window.open(this.msg.data, "_blank")
        // window.location.reload
    },
    jumptoself(){
        window.location.href=this.msg.data
        window.location.reload
    }
  },
  created() {
    this.getMessage();
  },
};
</script>

运行界面

在这里插入图片描述

点击 点击 jump_to_new_tab 按钮

会直接跳转到从后端传来的json数据中解析到的URL,注意它是在新的tab标签页打开的
在这里插入图片描述

点击首页中的 点击

会直接在根URL(IP:Port)后拼接上 ping
在这里插入图片描述

点击 点击 jump_to_self 按钮

会直接在本页面刷新,覆盖原页面,跳转到新的页面
在这里插入图片描述

注意

如果后端传到前端的json数据中不是URL,比如传过来的是 www.baidu.com,前端点击跳转的时候会是直接拼接到原URL后,如下所示:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/WU2629409421perfect/article/details/113704422