:onchange事件导致循环通过方法

时间:2019-05-21 13:10:58

标签: javascript vue.js event-handling axios

我有一个使用Vue.js制作的应用程序,该应用程序正在使用Axios发出多个发布请求。在我的组件之一中,我有一张桌子和一个选择框。选择框包含多个“教师组”,例如“ 4M07a”。每个导师组都有一堆我需要在表中显示的学生。我是通过执行:onchange事件并将所选值发送到我的方法来实现的。在我的方法中,我正在使用axios使用选定的值,教师名称和apikey进行发布请求。问题在于:onchange事件是通过我的方法引起的循环。当我在DevTools中查看“网络”选项卡时,我只会看到无限制的请求。我希望有人可以帮助我解决这个问题。

我尝试使用不同的事件处理程序,并将返回值放入我的方法中,但到目前为止没有任何效果。

我的选择框:

<select v-model="selectedValue" :onchange="getStudents(this.selectedValue)" class="select-klas form-control">
    <option> Selecteer een tutorgroep </option>
    <option v-for="(tutorklas, index) in tutorklassen" :key="index">{{ 
    tutorklas.id }}</option>
</select>

我的方法:

getStudents(event) {
            // zet data klaar om verzonden te worden
            const postTutorClassData = new FormData();
            postTutorClassData.append('docent', this.teachername)
            postTutorClassData.append('apikey', this.apikey)
            postTutorClassData.append('tutorgroep', event)

            // maak post request naar API
            axios.post(this.URL_TUTORKLAS, postTutorClassData)
            .then((response) => {
                this.docenten = response.data.docent;

                this.leerlingen = response.data.leerlingen;

                // force stop
                this.selectedValue = 'null';

            })
            .catch(function (error) {
                console.log(error);
            });
        },

它没有给出任何错误消息,只是通过我的方法不断循环。

2 个答案:

答案 0 :(得分:2)

:onchange不是侦听vue中的更改事件的正确语法,您也不需要将this.selectedValue传递给方法,因为它将在您的数据中可用(您没有访问模板中的this

尝试以下操作:

:onchange更改为:

@change="getStudents"

将您的getStudents方法更新为:

getStudents() {
    const postTutorClassData = new FormData();

    postTutorClassData.append('docent', this.teachername);
    postTutorClassData.append('apikey', this.apikey);
    postTutorClassData.append('tutorgroep', this.selectedValue) // remove event and use selected value

    axios.post(this.URL_TUTORKLAS, postTutorClassData).then(response => {
        this.docenten = response.data.docent;
        this.leerlingen = response.data.leerlingen;

        // this.selectedValue = 'null';
        // Changing this to be null will re-trigger the change event, causing your infinite loop
    }).catch(function (error) {
        console.log(error);
    });
},

答案 1 :(得分:1)

使用@change代替:onchange