微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在通过 Wordpress API 和 Vue.js 使用无头 CMS 时添加 wp: 特色图像以循环播放 如果有人对从第一个项目/教程 (nuxt.js) 派生的代码中实施 wp:featuredmedia 有任何建议,请告诉我

如何解决在通过 Wordpress API 和 Vue.js 使用无头 CMS 时添加 wp: 特色图像以循环播放 如果有人对从第一个项目/教程 (nuxt.js) 派生的代码中实施 wp:featuredmedia 有任何建议,请告诉我

想知道如何使用 wordpress Restful API 将 wordpress 特色图片实现到多个基于 vue.js/nuxt.js 的无头 CMS 方法

最初,我遵循了这个非常有用的教程 headless-cms with nuxt 并通过 wordpress api 创建了一个无头 CMS,并且当然将其应用于我的用例(这里是一个实时版本的链接 nuxt-headless-cms-webapp . 不幸的是,我一直无法弄清楚如何包含帖子的特色图片,因为它没有包含在本特定教程中。然后我做了一些研究并最终拼凑了另一个项目(vue.js),其中我能够实现特色图像。话虽如此,我想就原始教程的项目(因为根据我的理解,nuxt 提供更好的路由和 SEO 选项)根据 wp 特色图像实现我的工作代码方面的指导。谢谢提前寻求任何帮助!

首先,这里是原始教程 (nuxt) 项目的 index.js 中的 axios http 请求语法:

const siteURL = "https://indvillage.com"

export const state = () => ({
  posts: [],tags: []
})

export const mutations = {
  updatePosts: (state,posts) => {
    state.posts = posts
  },updateTags: (state,tags) => {
    state.tags = tags
  }
}

export const actions = {
  async getPosts({ state,commit,dispatch }) {
    if (state.posts.length) return
    

    try {
      let posts = await fetch(
        `${siteURL}/wp-json/wp/v2/posts?_embed`
      ).then(res => res.json())

      posts = posts
        .filter(el => el.status === "publish")
        .map(({ id,slug,title,excerpt,date,tags,content }) => ({
          id,content
        }))

      commit("updatePosts",posts)
    } catch (err) {
      console.log(err)
    }
  },async getMedia({ state,commit }) {
    if (state.media.length) return
    

    try {
      let media= await fetch(
        `${siteURL}/wp-json/wp/v2/media?_embed`
      ).then(res => res.json())


      commit("updatePosts",media)
    } catch (err) {
      console.log(err)
    }
  },async getTags({ state,commit }) {
    if (state.tags.length) return

    let allTags = state.posts.reduce((acc,item) => {
      return acc.concat(item.tags)
    },[])
    allTags = allTags.join()

    try {
      let tags = await fetch(
        `${siteURL}/wp-json/wp/v2/tags?page=1&per_page=40&include=${allTags}`
      ).then(res => res.json())

      tags = tags.map(({ id,name }) => ({
        id,name
      }))

      commit("updateTags",tags)
    } catch (err) {
      console.log(err)
    }
  }
}

接下来是实现上述逻辑的 index.vue 页面

template>
  <div>
    <app-masthead></app-masthead>
    <div class="posts">
      <main>
        <div class="post" v-for="post in sortedPosts" :key="post.id">
          <h3>
            <a :href="`blog/${post.slug}`">{{ post.title.rendered }}</a>
          </h3>
          <small>{{ post.date | dateformat }}</small>
          <div v-html="post.excerpt.rendered"></div>
          <a :href="`blog/${post.slug}`" class="readmore slide">Read more ⟶</a>
        </div>
      </main>
      <!--<aside>
        <h2 class="tags-title">Tags</h2>
        <div class="tags-list">
          <ul>
            <li
              @click="updateTag(tag)"
              v-for="tag in tags"
              :key="tag.id"
              :class="[tag.id === selectedTag ? activeClass : '']"
            >
              <a>{{ tag.name }}</a>
              <span v-if="tag.id === selectedTag">✕</span>
            </li>
          </ul>
        </div>
      </aside>-->
    </div>
  </div>
</template>

<script>
import AppMasthead from "@/components/AppMasthead.vue";

export default {
  components: {
    AppMasthead
  },data() {
    return {
      selectedTag: null,activeClass: "active"
    };
  },computed: {
    posts() {
      return this.$store.state.posts;
      _embed = true;
    },tags() {
      return this.$store.state.tags;
    },sortedPosts() {
      if (!this.selectedTag) return this.posts;
      return this.posts.filter(el => el.tags.includes(this.selectedTag));
    }
  },created() {
    this.$store.dispatch("getPosts");
  },methods: {
    updateTag(tag) {
      if (!this.selectedTag) {
        this.selectedTag = tag.id;
      } else {
        this.selectedTag = null;
      }
    }
  }
};

这是我的项目的链接,其中包含可用的 wordpress 特色图片https://indvillage.netlify.app/ 这是与我使用的 axIoUs http 请求相关的逻辑。 问题是,我如何在不破坏事物的情况下将 wp 特色图像方面的逻辑包含到初始 nuxt 教程中:

export default {
 data() {
   return {
     postsUrl: "https://indvillage.com/wp-json/wp/v2/posts",queryOptions: {
       per_page: 6,page: 1,_embed: true     
     },`
     
     posts: []
     
   };
 },methods: {
   // Get recent posts from wp
   getRecentMessages() {
     axios
       .get(this.postsUrl,{ params: this.queryOptions })
       .then(response => {
         this.posts = response.data;
         console.log("Posts retrieved!");
     
         })
         
         //document.getElementById("test").id = "testing";
       
       .catch(error => {
         console.log(error);
       });
   },getPostDate(date) {
     return moment(date).format("111");
   },},mounted() {
   this.getRecentMessages();
 }
}

接下来是显示解析信息的App.vue模板:

<template id="app">
  <body>
    <div class="row container">
      
  <!-- looping through and displaying the array bound posts in HTML -->
      
      <div class="col s4 m4" v-for="(post,index) in posts" :key="index" :id="'post'+index">
        <div class="card" id="test">
          <div class="card-image">
            
  <!-- rendering the post's wp:featuredmedia in the image portion of the html/css card -->
          
          <img
              v-if="post._embedded['wp:featuredmedia']"
              :src="post._embedded['wp:featuredmedia'][0].source_url"
            />
          </div>
          
    <!-- rendering the post.excerpt to the html/css card container --> 

          <div class="card-content" v-html="post.excerpt.rendered"></div>
          <div class="card-action">
    
    <!-- rendering the post title to the action portion of the html/css card -->

            <a href="#">{{ post.title.rendered }}</a>
          </div>
        </div>
      </div>
  </body>
</template>

如果有人对从第一个项目/教程 (nuxt.js) 派生的代码中实施 wp:featuredmedia 有任何建议,请告诉我


再次感谢!如有其他问题,请随时通过电子邮件发送

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。