gpt4 book ai didi

javascript - 如何在数据改变时自动更新vue组件而不刷新页面

转载 作者:行者123 更新时间:2023-12-02 22:47:22 25 4
gpt4 key购买 nike

我已经使用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>

最佳答案

我怀疑这一行: this.post =等待PostService.getPosts();应该 this.posts = wait PostService.getPosts(); 这是一个 Codepen关联。如果这不能解决您的问题,请确保 PostService 返回正确的对象。

关于javascript - 如何在数据改变时自动更新vue组件而不刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58341091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com