Vue3 <script setup> 中使用 beforeRouteEnter 实现公共页面回退到上一个页面

时间:2025-01-21 08:43:10

a-->c b-->c 想实现c返回到上一个页面 走了太多弯路

最终得出的解法

const onClickLeft = () => {
  (-1);
};

之前的解法 用组件内导航守卫

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  beforeRouteEnter(to, from, next) {
    next((e: any) => {
      if ( == "/index") {
         = "/index";
      }
      if ( == "/list") {
         = "/list";
      }
    });
  },
});
</script>
<script setup lang="ts">
import { reactive, ref, onMounted,nextTick } from "vue";
const { useRouter } = require("vue-router");

const router = useRouter();

let data = reactive({
  routerIndex: "",
});

defineExpose({ data });
//返回
//将回调推迟到下一个 DOM 更新周期之后执行
const onClickLeft = async () => {
  await nextTick();
  if ( == "/index") {
    ({
      path: "/index",
    });
  }
  if ( == "/list") {
    ({
      path: "/list",
    });
  }
};

// const onClickLeft = () => {
//   (-1);
// };

onMounted(() => {
  //   (); 
});
</script>