【发布时间】:2022-09-28 20:20:22
【问题描述】:
我正在用 Nuxt.js 编写一个博客,并且连接到 ButterCMS 的 API。
我想获取帖子的日期(文本),然后对其进行切片。我的问题是它返回一个错误:TypeError: null is not an object (evaluating \'document.querySelector(\".date\").textContent\')。当我在 JS 控制台中执行相同的代码时,它正在工作。我已经尝试将事件侦听器添加到页面的加载中,但它没有改变任何东西。这是我的代码:
document.querySelector(\".date\").textContent.slice(0, 29);
<template>
<div id=\"blog-home\">
<div class=\"recent-article-feed\">
<div v-for=\"(post, index) in posts\" :key=\"post.slug + \'_\' + index\">
<router-link :to=\"\'/blog/\' + post.slug\">
<div class=\"article\">
<div class=\"dark-window\">
<div class=\"text-box\">
<h2 class=\"title\">{{ post.title }}</h2>
<div>
<span class=\"author\">
<i class=\"fa-solid fa-user\"></i> Par Maxime Hamou
</span>
∙
<span class=\"date\">
<i class=\"fa-solid fa-calendar-days\"></i>
{{ post.published }}
</span>
</div>
<p class=\"description\">
{{ post.summary }}
</p>
<p class=\"read\">Lire l\'article →</p>
</div>
</div>
</div>
</router-link>
</div>
</div>
</div>
</template>
<style>
@import url(\"../css/index.css\");
@import url(\"../css/components/recent-article-feed.css\");
</style>
<script>
import { butter } from \"~/plugins/buttercms\";
export default {
data() {
return {
posts: [],
};
},
methods: {
getPosts() {
butter.post
.list({
page: 1,
page_size: 10,
})
.then((res) => {
// console.log(res.data)
this.posts = res.data.data;
});
},
},
created() {
this.getPosts();
},
};
</script>
-
日期可能是从 API 调用或您的依赖项的 js 中加载的,并且您的代码可能在实际加载日期之前执行。在 Chrome 开发工具的网络选项卡中,您可以查看日期是否从 API 调用中加载。
-
您将
document.querySelector(\".date\").textContent.slice(0, 29);放在该代码的哪个位置?这听起来很像 Why does jQuery or a DOM method such as getElementById not find the element? 的复制品 -
这段代码看起来像您正在使用 Vue.js。你确定吗?
-
您根本不应该使用
document.querySelector来访问日期!只需使用this.posts[0].published!
标签: javascript