0

下面是一个非常简单的Nativescript Vue 示例。如下所示,它显示了 5 个帖子标题的列表。

因此,只要我只用于 computed将数据返回到模板,上面的测试就可以开始了。但是,如果我尝试使用create()mounted()事件/生命周期挂钩来设置posts属性,我将在显示中一无所获。这些console.log行从不显示消息,因此它们永远不会触发。为什么不?

此外,如果我尝试使用 fetch(调用我的fetchPosts()方法)从测试 restapi 中提取帖子,我将没有得到任何数据并且console.error什么也没有显示。为什么不?

<template>
<Page class="page">
    <ActionBar class="action-bar">
    <Label class="action-bar-title" text="Home"></Label>
    </ActionBar>
    <ScrollView>
    <StackLayout class="home-panel">
        <!--Add your page content here-->
        <Label v-for="post in posts" :text="post.title" :key="post.id"/>
    </StackLayout>
    </ScrollView>
</Page>
</template>

<script>
export default {
//   posts: [],
//   create() {
//     console.log("create event fired");
//     this.posts = this.getPosts();
//   },
//   mounted() {
//     console.log("mounted event fired");
//     this.posts = this.getPosts();
//   },
computed: {
    posts() {
    //return this.fetchPosts();
    return this.getPosts();
    }
},
methods: {
    fetchPosts() {
    fetch("https://jsonplaceholder.typicode.com/posts")
        .then(res => res.json())
        .then(res => {
        console.log("fetch response", res);
        return res;
        })
        .catch(err => {
        console.error(err);
        return [{ id: 0, title: "Error: " + err }];
        });
    },
    getPosts() {
    return [
        {
        userId: 1,
        id: 1,
        title:
            "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        body:
            "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
        },
        {
        userId: 1,
        id: 2,
        title: "qui est esse",
        body:
            "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
        },
        {
        userId: 1,
        id: 3,
        title: "ea molestias quasi exercitationem repellat qui ipsa sit aut",
        body:
            "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
        },
        {
        userId: 1,
        id: 4,
        title: "eum et est occaecati",
        body:
            "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
        },
        {
        userId: 1,
        id: 5,
        title: "nesciunt quas odio",
        body:
            "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
        }
    ];
    }
}
};
</script>

<style scoped lang="scss">
// Start custom common variables
@import "../app-variables";
// End custom common variables

// Custom styles
.fa {
color: $accent-dark;
}

.info {
font-size: 20;
}
</style>
4

2 回答 2

2

我在您的代码中发现了一些问题:

  1. 正确的生命周期钩子名称是 created, notcreate
  2. posts列表应该在里面data

    data() {
        return {
            posts: []
        };
    },
    
  3. thefetchPosts()不返回任何内容,但您希望返回posts. 您必须设置posts内部then回调:

    fetchPosts() {
        fetch("https://jsonplaceholder.typicode.com/posts")
            .then(res => res.json())
            .then(res => this.posts = res)
            .catch(err => console.error(err));
    }
    

    这是因为fetch返回一个Promise. 问:如何从 中返回数据Promise?答:你不能

完整代码:

<script>
export default {
    data() {
        return {
            posts: [{
                title: '1 Title',
                id: 1
            }]
        };
    },
    created() {
        console.log("create event fired");
        this.posts = this.fetchPosts();
    },
    mounted() {
        console.log("mounted event fired");
        this.fetchPosts();
    },
    methods: {
        fetchPosts() {
            return fetch("https://jsonplaceholder.typicode.com/posts")
                .then(res => res.json())
                .then(res => this.posts = res);
        }
    }
};
</script>

代码在这里进行了测试。

于 2019-02-03T17:45:34.317 回答
1

对我来说,它也没有触发,而不是使用 mount 或 created 我在页面元素上添加了一个加载事件

<template>
    <page @loaded="startMyApp">
    ......
</template>
<script>
  export default {
    data() {
      return {
      }
    },
   methods: {
        startMyApp()
        {
        }
  }
</script>
于 2019-03-28T03:20:03.487 回答