【问题标题】:How to create back button using NuxtJS <nuxt-link />?如何使用 NuxtJS <nuxt-link /> 创建后退按钮?
【发布时间】:2020-09-10 01:17:32
【问题描述】:

我正在处理一个相当新的 Nuxt 项目,但在设置后退按钮时遇到了问题。我什至查看了仍然不想工作的“vue-router-back-button”包(我遇到了不相关的错误)。使用我拥有的代码,链接想要导航到用户当前所在的同一页面,而不是前一个页面。我确实在我的服务器上收到了一个错误消息,指出有一个 Invalid prop: type check failed for prop "to". Expected String, Object, got Function.,但是我可以让后退按钮动态化吗?

<template>
  <div class="page-title-wrapper">
    <nuxt-link
      v-if="back"
      :to="to"
      class="back-wrapper">
      <icon
        name="angle-left"
        fill="#9e9e9e"
        height="20px"
        width="20px"
        class="d-flex" />
      <p class="display-1 grey--text">
        Back
      </p>
    </nuxt-link>
    <h1 class="display-3 text-center">
      {{ text }}
    </h1>
  </div>
</template>

<script>
  export default {
    props: {
      back: {
        type: Boolean,
        default: false,
      },
      text: {
        type: String,
        default: 'Page'
      }
    },

    methods: {
      to() {
        this.$router.go(-1);     <---- evaluates to current page?
      },
    }
  }
</script>

【问题讨论】:

    标签: nuxt.js


    【解决方案1】:

    this.$router.go(-1)

    使用 Vue Router(Nuxt 使用)返回历史步骤的命令:

    this.$router.go(-1)
    

    使用点击监听器,在函数中触发它,如下所示:

    模板:

    <div @click="goToPrev()">My Button</div>
    

    方法:

    methods: {
      goToPrev() {
    
        // ...
        // Do other logic like logging, etc.
        // ...
    
        // Tell router to go back one
        this.$router.go(-1);
      },
    }
    

    另一个例子:

    使用 Vuetify 框架及其按钮元素 (&lt;v-btn&gt;):

      <template>  
        <v-btn text :ripple="false" class="back-wrapper" @click="to">
          <icon name="angle-left" fill="#9e9e9e" height="20px" width="20px" class="d-flex" />
          <p class="display-1 grey--text">
            Back
          </p>
        </v-btn>
      </template>
    
      <script>
        methods: {
          to() {
            this.$router.go(-1)
          },
        }
      </script>
    

    【讨论】:

      【解决方案2】:

      您也可以通过检查窗口历史长度来使用它。如果窗口历史为 1 或小于 1,那么它将返回您的主页。更实用。

       window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-26
        • 1970-01-01
        • 2020-11-18
        • 2022-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多