VueJS如何将表单参数推送到Vue路由器?

时间:2019-08-06 13:55:43

标签: vue.js vuejs2 vue-router

我正在尝试创建一个编辑表单。如何从url(vue-router)中获取参数并将其传递给html表单?以及如何将表单数据推送到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>

所以我想在模型和vue-router之间绑定数据。当我打开edit.html#/ user = 5&team = 3&bday = 1991-01-10时,必须填写适当的多选字段。怎么做?

1 个答案:

答案 0 :(得分:1)

您可以在路线URL中使用query

将所有所有multiselect字段存储在一个计算变量中,并添加观察者以在参数发生任何更改时将新参数推送到您的URL:

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

创建页面后,使用函数获取查询并设置表单变量:

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
    }
}