ホームページ >CMS チュートリアル >&#&プレス >VueでWordPressプラグインを構築します
このチュートリアルは、プログレッシブJavaScriptフレームワークであるVue.jsを使用して最新のWordPress UIを構築する方法を示しています。 Fetch APIを介してWordPress REST APIと対話するVUEインターフェイスを使用したシンプルなプラグインを作成します。
重要な概念:このガイドは、ショートコードを登録するWordPressプラグインの作成、Vue.jsの統合、
エンドポイントと対話して最近の投稿を表示するVUEアプリの構築をカバーしています。/wp-json/wp/v2/posts?filter[orderby]=date
を使用したリアルタイムの更新も表示されます。mounted()
に基本的な知識を想定しています
setInterval()
WordPressプラグインの構築:
プラグインディレクトリの作成:
ディレクトリ。
vueplugin
wp-content/plugins
vueplugin.php
vueplugin.php
ショートコードを登録:
<code class="language-php"><?php /* Plugin Name: Latest Posts Description: Latest posts shortcode with Vue.js Version: 1.0 */</code>に追加して、
これは、vue.jsライブラリとカスタムJavaScriptファイル()をエンキューします。
vueplugin.php
latestPosts
<code class="language-php">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');</code>プラグインをアクティブにします:
WordPress管理ダッシュボードを介してプラグインをアクティブにします。
latest-posts.js
ショートコードをテストするためにを投稿またはページに追加します。
[latestPosts]
このコードを使用して、プラグインディレクトリに
を作成してください:
latest-posts.js
検証:latest-posts.js
スクリプトもページソースに含める必要があります。
<code class="language-javascript">(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> ` }); })();</code>
結論:
この拡張されたチュートリアルは、Vue.jsをWordPressプラグインに統合して、ダイナミックでリアルタイムのユーザーエクスペリエンスを提供する完全な実用的な例を提供します。 特定のテーマに必要に応じて、パスとスタイリングを調整することを忘れないでください。 元の入力からのFAQは、修正および拡張されたチュートリアル内で適切にカバーされているため、省略されています。
以上がVueでWordPressプラグインを構築しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。