Vue.js Uncaught TypeError: Cannot read properties of undefined

Vue.js Uncaught TypeError: Cannot read properties of undefined

我是 Vue.js 的新手,无法理解为什么会出现此错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'contacts')

这是导致错误的方法:

methods: {
    sortContacts: () => {
        return _.sortBy(self.contacts, [(contact) => {
            return contact.unread;
        }]).reverse();
    }
}

Contacts是组件数据中的一个数组,为什么访问不到呢?

我根据要求提供了整个脚本,它就在这段文字的下面。代码是用 Vue.js 写的,我没有包括上面的 HTML 是不是没必要。

<script>
import Conversation from "../components/Conversation";
import ContactsList from "../components/ContactsList";
import { mapState } from 'vuex';

export default {
    components: {Conversation, ContactsList},
    data() {
        return {
            selectedContact: null,
            messages: [],
            contacts: []
        }
    },
    computed: {
        ...mapState({
            userId: state => state.user.id
        }),
    },
    mounted() {
        axios.get('/api/contacts')
            .then((response) => {
                const contacts = response.data.data;

                this.contacts = _.sortBy(contacts, [(contact) => {
                    return contact.unread;
                }]).reverse();
            });
    },
    watch: {
        userId(userId) {
            Echo.private(`messages.${userId}`)
                .listen('NewMessage', (e) => {
                    this.handleIncoming(e.message);
                });
        }
    },
    methods: {
        addMessage(message) {
            this.messages.push(message);
        },
        async logout() {
            try {
                axios.post("/logout");
                this.$store.dispatch("logout");
                this.$router.push({ name: "auth-login" });
            } catch (error) {
                this.$store.dispatch("logout");
                this.$router.push({ name: "auth-login" });
            }
        },
        getMessages(contact) {
            this.updateUnreadCount(contact, true);
            axios.get(`/api/messages/${contact.id}`)
                .then((response) => {
                    this.messages = response.data.data;
                    this.selectedContact = contact;
                });
        },
        handleIncoming(message) {
            if (this.selectedContact && message.from === this.selectedContact.id) {
                this.addMessage(message);
            }

            this.updateUnreadCount(message.from_contact, false);
        },
        updateUnreadCount(contact, reset) {
            this.contacts = this.contacts.map((single) => {
                if (single.id !== contact.id) {
                    return single;
                }

                if (reset) {
                    single.unread = 0;
                } else {
                    single.unread += 1;
                    this.contacts = this.sortContacts();
                }

                return single;
            });
        },
        sortContacts: () => {
            return _.sortBy(this.contacts, [(contact) => {
                return contact.unread;
            }]).reverse();
        }
    }
}
</script>

我制作了一个小片段来进行相同的排序。

除了 self 错误之外,我已经将您的 sortContacts 方法符号更改为:

sortContacts: function () {
    return _.sortBy(this.contacts, [(contact) => {
        return contact.unread;
    }]).reverse();
}

并且按预期工作。

var app = new Vue({
    el: "#app",
    data() {
        return {
        result: [{name: 'adam', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}],
        };
    },
    methods: {
        sortClick: function (){
            this.result = this.sortContacts();
        },
        sortContacts: function (){
            console.log(this.result)
            return _.sortBy(this.result, [(r) => {
                return r.name;
            }]).reverse();
        }
    },
});
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
  </head>
  <body>
      <div id="app">
        {{ result }}
        <button v-on:click="sortClick">Reverse</button>
      </div>
  </body>
</html>

请同时验证您 mounted 部分中的代码段 const contacts = response.data.data;

通常请求的内容排在第一个data。确保您的内容确实在第二个 data 属性中。 request 中的简单 console.log 就可以了。