[Vuejs]-Vue.js – How to capture a URL parameter as a hidden input value

2👍

The way you can do this with Vue is using vue-router and accessing the $route.query object.

For instance, when the URL has ?key=somekey, the $route.query object is `{key: “somekey”}.

Here’s a demo CodeSandbox showing how you could use it.

Relevant code:

// main.js
import Vue from "vue";
import VueRouter from "vue-router";
import PasswordReset from "./PasswordReset";

Vue.use(VueRouter);

var router = new VueRouter({
  mode: 'history',
  routes: [{
    path: '/',
    component: {
      template: `<div>
   You are at '/'.<br>
     Click to simulate an external link user:
     <a href="https://lrrwkyv7k7.codesandbox.io/passwordreset?key=somekey">
     https://lrrwkyv7k7.codesandbox.io/passwordreset?key=somekey
     </a>
      </div>`
    }
  }, {
    path: '/passwordreset',
    component: PasswordReset
  }]
});

new Vue({
  el: "#app",
  router: router,
  template: '<router-view></router-view>'
});
// PasswordReset.vue
<template>
  <div id="app">
    <p>Hello, user.</p>
    <form action="" @submit="submit">
    Type some new password: <input type="text" name="newpass" v-model="newPass">
    <input type="hidden" name="key" :value="hiddenKey">
    <button>Send</button>
    </form>
    <hr>
    <div class="debug">
        Object that will be sent:
        <pre>{{ $data }}</pre>

        <a href="/">click here to get back to home</a>
    </div>
  </div>
</template>

<script>
export default {
  name: "PasswordReset",
  data() {
    return {
      newPass: "",
      hiddenKey: ""
    };
  },
  mounted() {
    this.hiddenKey = this.$route.query.key;
  },
  methods: {
    submit(event) {
      alert('We would have sent:\n'+JSON.stringify(this.$data, null, 2));
      event.preventDefault(); // don't submit now, just testing...
    }
  }
};
</script>

Leave a comment