0

I want to pass an URL parameter into the value of the input:

<input id="para" type=text v-model="recipient">

I have a URL with the param www.website.com?para=test , how can I inject that param on page loaded into the input?

I have done it with Jquery before, but I don't know how to achieve this in VUE. Here is the Jquery code that works:

        <script>
            $(document).ready(function() {
            function getURLParameter(e) {
              return decodeURI((new RegExp(e + "=(.+?)(&|$)").exec(location.search) || [, ""])[1]);
            }

            if (getURLParameter("Para") === "") {
              console.log("No URL param value found.");
            } else {
                console.log(getURLParameter("Para"));
              $("#para").value = getURLParameter("Para");
            }
        });
        </script>

Thanks a lot

2
  • Are you using Vue Router? Commented Sep 23, 2020 at 0:14
  • Hi Phil, no, I'm not using Router Commented Sep 23, 2020 at 9:31

2 Answers 2

1

You can parse the query string using URLSearchParams() and then assign the value to your recipient data property

<template>
  <div>
    <input id="para" type="text" v-model="recipient">
  </div>
</template>

<script>
export default {
  data: () => ({ recipient: "" }),
  created () {
    const params = new URLSearchParams(location.search)
    this.recipient = params.get("para")
  }
}
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

Hi there Phil, the problem is the input is on a non-vue view, so it's outside the <template></template>
Doesn't sound like your question has anything to do with Vue
Hi Phil, I had already defined recipient so it was giving me error. This works like a charm! Thanks a lot!
1

In your created method, you could assign the v-model value to the returned value of the function call. You would first have to create the getURLParameter function in your methods and then call it in the created method. So this way,

created(){
 this.recipient = this.getURLParameter("Para")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.