【问题标题】:How to automatically update vue component when data changed without refresh page如何在数据更改而不刷新页面时自动更新vue组件
【发布时间】:2020-02-08 23:19:32
【问题描述】:

我使用 axios 获取数据。但似乎 vue 组件在单击事件后和数据更改时没有更新。所以我必须刷新页面才能更新页面上的数据。你有什么简单的方法可以解决这个问题吗?

这是模板中的代码。

<template>
  <div class="container">
    <h1>Latest Posts</h1>
    <div class="create-post">
        <label for="create-post">Add new post...</label>
        <input type="text" id="create-post" v-model="text" placeholder="Create a post">
        <button v-on:click="createPost">Post!</button>
    </div>

    <hr>

    <p class="error" v-if="error">{{ error }}</p>

    <div class="posts-container">
      <div class="post" v-for="(post, index) in posts" v-bind:item="post" v-bind:index="index" v-bind:key="post._id">
        {{`${post.createdAt.getDate()}/${post.createdAt.getMonth()}/${post.createdAt.getFullYear()}`}}
        <p class="text" id="example">{{post.text}}</p>
      </div>
    </div>

  </div>
</template>

这是脚本中的代码


<script>
import PostService from '../PostService';

export default {
  name: 'PostComponent',
  data() {
    return {
      posts: [],
      error: '',
      text: ''
    }
  },
    computed: {
      postText: function() {
        return this.post.text
      }
    },
    watch: {

    },
  async created() {
    try {
      this.posts = await PostService.getPosts();
      console.log(this.$el.textContent) 
    } catch(err) {
      this.error = err.message;
    }
  },
  methods: {
    async createPost() {
      await PostService.insertPost(this.text);
      this.post = await PostService.getPosts();
    }
  }
}
</script>

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    我怀疑这条线: this.post = await PostService.getPosts(); 应该 this.posts = await PostService.getPosts(); 这是Codepen 链接。如果这不能解决您的问题,请确保 PostService 返回正确的对象。

    【讨论】:

    • 哦,非常感谢。那是我犯的一个愚蠢的错误。但我只是想知道为什么我没有收到任何未定义“post”的错误消息。无论如何,非常感谢!
    猜你喜欢
    • 2020-02-29
    • 2018-10-08
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    相关资源
    最近更新 更多