【问题标题】:Vuejs:访问特定的 URL 段
【发布时间】:2022-01-22 09:22:22
【问题描述】:

我有一个路线/网址:

例如。 http://localhost:8080/qr-codes

我想访问第一段

qr-codes

我该怎么做?

我曾经在 Laravel 中可以做这样的事情

请求::segment(1);

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vue-router


    【解决方案1】:
    const getUrlPathSegments = () => (
      (new URL(window.location.href)).pathname.split('/').filter(Boolean)
    )
    

    例如,当您在当前 stackoverflow 页面上调用该函数时,您会得到:

    getUrlPathSegments() === ['questions', '70427242', 'vuejs-accessing-specific-url-segment']
    
    getUrlPathSegments()[0] === 'questions'
    

    【讨论】:

      【解决方案2】:

      使用URL.pathnameString#split

      const str = 'http://localhost:8080/qr-codes';
      
      const firstSegment = (new URL(str)).pathname.split('/')[1];
      
      console.log(firstSegment);

      Vue 演示:

      new Vue({
        el: "#app",
        computed: {
          path: function() {
            const firstSegment = (new URL(window.location.href)).pathname.split('/')[1];
            return `${firstSegment}/create`;
          }
        }
      });
      <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
      
      <div id="app">{{path}}</div>

      【讨论】:

      • 有单行方式吗?我将把它添加到我的创建按钮中。
      • 前。 /qr-codes/创建
      • 第一段需要是动态的......我将其作为问题传递。
      • @code8888 你可以像上面那样对它们进行分组。
      • 你能提供更多关于你想要做什么的背景吗?
      猜你喜欢
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 2012-01-24
      • 2011-06-18
      相关资源
      最近更新 更多