programing

Vue 2 - 메서드 내에서 계산된 접근 방법

goodcopy 2022. 7. 29. 23:15
반응형

Vue 2 - 메서드 내에서 계산된 접근 방법

오브젝트를 포함하는 배열을 루프하여 이들 오브젝트에서 작성자 이름 목록을 가져옵니다.

이것을 하기 위해 나는 내가 쓸 방법을 쓰고 싶다.forEach()통해.그러나 어레이를 포함하는 계산된 속성에 액세스할 수 없는 경우console.log(articles)또는console.log(this.newsFeed)그것은 되돌아온다undefined또는 그냥 공백입니다.

분명히 내가 뭔가 잘못하고 있는 것 같은데...

코드는 다음과 같습니다.

new Vue({
    el: '#feed',
    data: {
        newsFeed: "",
},
created: function() {
    console.log('running');
    this.getData();
    this.filterAuthors();
},
computed: 
{
    articles: function() {
        var articles = this.newsFeed.articles;
        return articles;
    },
}, 
methods: 
{
    getData: function() {
        var newsFeed = this.$http.get('https://newsapi.org/v1/articles?source=the-next-web&sortby=latest&apikey='+ apikey).then(response => {
            this.newsFeed = response.body;
        }, response => {
            console.error(error);
        });
    },
    filterAuthors: function() {

        var articles = this.newsFeed.articles;
        var authorsArray = [];

        console.log(articles);

        // commented out while troubleshooting above
        // articles.forEach(function(article) {
        //  // var authors = article.author;
        //  // authorsArray.push(authors);
        //  console.log(authors);
        // });

        // return authorsArray;
    }
}
});

를 사용하여 발신한HTTP 콜this.$http는 비동기입니다.비동기이므로 콜이 종료될 때까지 대기하도록 코드를 지시해야 합니다.

에서getData다음과 같이 쓸 수 있습니다.

getData: function() {
    return this.$http.get('https://newsapi.org/v1/articles?source=the-next-web&sortby=latest&apikey='+ apikey)
    .then(response => {
        this.newsFeed = response.body;
    }, err => {
        console.error(err);
    });
}

그럼 당신의 글을 쓰세요.created기능하다filterAuthors메서드는 콜 종료 후에 실행됩니다.

created: function() {
    console.log('running');
    this.getData()
    .then(() => {
        this.filterAuthors();
    });
}

또한 계산된 변수는 다음과 같이 지정됩니다.articles이 때문에, 다음의 방법으로 액세스 할 수 있습니다.this.articles,것은 아니다.this.newsFeed.articles.

언급URL : https://stackoverflow.com/questions/45426452/vue-2-how-to-access-computed-within-method

반응형