簡體   English   中英

如何將對象數組分配給 Vue 組件中的空數組?

[英]How do I assign an array of objects to an empty array in a Vue component?

我正在嘗試編寫我的第一個使用 Vue 組件的 Laravel 程序。 我正在使用 Laravel 8.x 和 Vue 2.x 並在 Windows 10 上運行。我正在模仿一個展示如何操作的視頻 不幸的是,並非他所做的一切都對我有用。 昨天這里的一些人在解決我當時遇到的問題時對我很有幫助,但現在我有一個我無法弄清楚的新問題。

他正在使用 Axios 執行獲取請求,以讀取先前放入 Vue 組件中 MySQL 表的數據。 Axios 返回包含數據的響應,然后將其分配給組件的 data() 區域中的初始化空數組。 他將空數組定義如下:

todos: '',

執行 Axios get 的方法如下所示:

getToDos() {
        debugger;
        axios.get('/todo')
        .then(function (res) {
            if (res.data.length == 0) console.log("Table is empty");
            else {
                this.todos = res.data
            }
            })
        .catch(function (error) {
            console.log(error);
            })
    },

如您所見,他只是將所有 res.data(看起來是一個對象數組)分配給 data() 區域中的 todos 數組。 當他執行代碼時,它工作正常,但他使用的是 Laravel 7.x,而我使用的是 8.x。 當我嘗試執行此代碼時,Chrome 調試器中出現錯誤:

TypeError: this is undefined

其中突出顯示了賦值語句(this.todos = res.data)。 我還是 Javascript 的新手,而且我還不熟悉這些成語,但在我看來,todos 好像被定義為一個空字符串並被分配了一個對象數組,所以我真的希望當他執行它時會失敗但它沒有。 也許這與他使用 Laravel 7.x 有關?

無論如何,我做了一些研究,並在這段代碼中嘗試了一堆變體,但是當我將某些東西分配給 todos 變量時,我總是收到相同的錯誤消息,即使我將其定義為

todos: []

或者

todos: new Array()

我嘗試編寫一個 for 循環並將每個 Object 從 res.data 推送到 todos 中。 沒有任何效果。 有人可以告訴我為什么他的代碼有效以及為什么它不適合我嗎? 我只是想將 res.data 放在我可以在我的模板中訪問它的地方,以便我可以顯示相關數據。

編輯:這是整個組件。

    <template>
    <div class="container">
        <form @submit.prevent="addTask"> 
            <div class="input-group mb-3 w-100">
                <input type="text" v-model="form.todo" class="form-control" placeholder="Enter new task" aria-label="Enter new task" aria-describedby="button-addon2">
                <div class="input-group-append">
                    <button class="btn btn-success" type="submit" id="button-addon2">Add new task</button>
                </div>
            </div>
        </form>
        <div class="w-25">
            <h1 class="text-white">...</h1>
            <div v-for="todo in todos" :key="todo.id" class="w-100 text-white">
                {{ todo.title }}
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                todos: '',

                form: new Form({
                    title: '',
                })

            } 
        },
        methods: {
            getToDos() {
                debugger;
                axios.get('/todo')
                .then(function (res) {
                    if (res.data.length == 0) console.log("Table is empty");
                    else {
                        this.todos = res.data
                        // var id = 0;
                        // var title = '';
                        // var completed = false;
                        // for (var ix=0; ix<res.data.length; ix++) {
                        //     id = res.data[ix].id;
                        //     title = res.data[ix].title;
                        //     completed = res.data[ix].completed;
                            // var oneToDo = new Object(res.data[ix]);
                            // this.todos.push(oneToDo);
                        // }   
                    }
                    })
                .catch(function (error) {
                    console.log(error);
                    })
            },
            addTask() {
                let data = new FormData();
                data.append('todo', this.form.todo);
                axios.post('/todo', data)
                .then(function (response) {
                    console.log(response);
                    this.form.reset;
                    this.getToDos();
                    })
                .catch(function (error) {
                    console.log(error);
                    })
            }
        },
        mounted() {
            console.log('ToDoComponent mounted.');
            this.getToDos();
        }
    }
</script>

<style lang="scss" scoped>
.container {
    padding-top: 5em;
}
</style>

使用箭頭 function。 像這樣 for.then 部分

.then((res) => {
    //rest of code
})

function(){ //code } 中this的閉包是 function 本身。 如果您想訪問您定義 function 的 object 的this ,您將需要使用箭頭 function,如下所示。

var obj = {
    getToDos() {
       // this here refer to obj
       axios.get('/todo')
        .then( res =>  {
           this.todos =  res.data
       })
    }

}

有關 js 中的閉包的更多信息: https://www.w3schools.com/js/js_function_closures.asp https://medium.com/@vmarchesin/javascript-arrow-functions-and-closures-4e53aa30b774

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM