ATLANT1S
ATLANT1S

Reputation: 31

VueJS how to push form params to vue router?

I'm trying to create an edit form. How can I get the parameters from the url (vue-router) and pass them to the html form? And how can I push my form data to url?

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<form class="form-horizontal">

    <!-- MultiSelect -->
    <div class="form-group">
      <label class="col-xs-2 col-md-1 control-label">User</label>
      <div class="col-xs-10 col-md-3">
        <multiselect
            v-model="user"
            :options="userList"
            :searchable="true"
            label="Name"
            track-by="Name">
        </multiselect>
      </div>
    </div>

    <!-- MultiSelect -->
    <div class="form-group">
      <label class="col-xs-2 col-md-1 control-label">Team</label>
      <div class="col-xs-10 col-md-3">
        <multiselect
            v-model="team"
            :options="teamList"
            :searchable="true"
            label="Name"
            track-by="Name">
        </multiselect>
      </div>
    </div>

    <!-- DatePicker -->
    <div class="form-group">
      <label class="col-xs-2 col-md-1 control-label">Birthday</label>
      <div class="col-xs-10 col-md-3">
        <date-picker
            v-model="calendarDate"
            :shortcuts="shortcuts"
            :first-day-of-week="1"
            appendToBody
         ></date-picker>
      </div>
    </div>

    <!-- Button -->
    <div class="form-group">
      <label class="col-md-1 control-label"></label>
      <div class="col-md-4">
        <button @click="EditUser" class="btn btn-primary">Edit</button>
      </div>
    </div>

</form>

So I want to bind data between the models and vue-router. When I open edit.html#/user=5&team=3&bday=1991-01-10 appropriate multiselect fields must be filled. How to do it?

Upvotes: 1

Views: 1591

Answers (1)

Cathy Ha
Cathy Ha

Reputation: 1677

You can use query in your route URL:

Store all of your multiselect fields in a computed variable, and add a watcher to push the new parameters to your URL when there are any changes in the parameter:

computed: {
    queryParams({ user, team, calendarDate }) {
        return {
            user: user,
            team: team,
            bday: calendarDate
        }
    }
},
watch: {
    queryParams() {
        this.$router.push( name: this.$route.name, query: this.queryParams })
    }
}

When your page is created, use a function to get the query and set the form variables:

created() {
    this.setQueryParams();
},
methods() {
    setQueryParams() {
        const query = this.$route.query;
        this.user = query.user;
        this.team = query.team; 
        this.calendarDate = query.bday;
        // you might need to do some formatting for the birthday and do some checks to see if the parameter exists in the query so you don't get errors
    }
}

Upvotes: 1

Related Questions