本教程展示了如何使用渐进的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中文网其他相关文章!