本教程展示瞭如何使用漸進的JavaScript框架Vue.js構建現代WordPress UI。 我們將通過fetch api與WordPress Rest API進行VUE接口創建一個簡單的插件。
密鑰概念:
/wp-json/wp/v2/posts?filter[orderby]=date
端點交互以顯示最新帖子的VUE應用程序。 mounted()
的實時更新。 setInterval()
>
>構建WordPress插件:>
>創建插件目錄:>在您的WordPress 目錄中創建一個文件夾(例如,vueplugin
)。
wp-content/plugins
:vueplugin.php
vueplugin.php
<?php /* Plugin Name: Latest Posts Description: Latest posts shortcode with Vue.js Version: 1.0 */
這引起了vue.js庫和自定義JavaScript文件(vueplugin.php
)。
latestPosts
function handle_shortcode() { return '<div id="mount"></div>'; } add_shortcode('latestPosts', 'handle_shortcode'); function enqueue_scripts() { global $post; if (has_shortcode($post->post_content, "latestPosts")) { wp_enqueue_script('vue', 'https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js', [], '2.5.17'); wp_enqueue_script('latest-posts', plugin_dir_url(__FILE__) . 'latest-posts.js', [], '1.0', true); } } add_action('wp_enqueue_scripts', 'enqueue_scripts');
激活插件:latest-posts.js
>通過您的WordPress admin儀表板激活插件。
測試快捷代碼:
[latestPosts]
在您的插件目錄中使用此代碼:
latest-posts.js
驗證:latest-posts.js
檢查瀏覽器的開發人員控制台“已安裝了組件”和獲取的帖子。 您的頁面源也應包含
(function() { var vm = new Vue({ el: '#mount', data: { posts: [] }, mounted: function() { this.fetchPosts(); setInterval(this.fetchPosts.bind(this), 5000); }, methods: { fetchPosts: function() { fetch('/wp-json/wp/v2/posts?filter[orderby]=date') .then(response => response.json()) .then(data => this.posts = data); } }, template: ` <div> <h1>My Latest Posts</h1> <div v-if="posts.length > 0"> <ul> <li v-for="post in posts"> <a :href="https://www.php.cn/link/f417d05af72b37f956c906aea42d1511">{{ post.title.rendered }}</a> </li> </ul> </div> <div v-else> <p>Loading posts...</p> </div> </div> ` }); })();
結論:
以上是用VUE構建WordPress插件的詳細內容。更多資訊請關注PHP中文網其他相關文章!