wordpress vue

tech2022-08-08  151

wordpress vue

In this tutorial, we’ll learn how to integrate Vue.js with a WordPress plugin to provide a modern UI experience to our WordPress users.

在本教程中,我们将学习如何将Vue.js与WordPress插件集成在一起 ,从而为WordPress用户提供现代的UI体验。

Vue.js is a very popular progressive JavaScript library for building modern and rich user interfaces similar to Angular and React in terms of popularity, performance and component-based architecture. We’ll dive into the entire process of building a very simple WordPress plugin with a Vue interface that interacts with the WordPress REST API through the JavaScript Fetch API.

Vue.js是一个非常流行的渐进式JavaScript库,用于在流行度,性能和基于组件的体系结构方面构建类似于Angular和React的现代且丰富的用户界面。 我们将深入研究构建具有Vue界面的非常简单的WordPress插件的整个过程,该插件通过JavaScript Fetch API与WordPress REST API交互。

We’ll create a shortcode that will allow us to add a latest published posts widget in our WordPress website. The UI of the widget is a Vue app which fetches the latest published posts via the /wp-json/wp/v2/posts?filter[orderby]=date WP-API endpoint.

我们将创建一个简码,以允许我们在WordPress网站中添加最新发布的帖子小部件。 窗口小部件的UI是一个Vue应用程序,可通过/wp-json/wp/v2/posts?filter[orderby]=date WP-API端点获取最新发布的帖子。

This tutorial assumes some familiarity with Vue.js. We’ll see how to create a Vue instance, use life-cycle hooks like mounted(), and also the JavaScript Fetch API to interact with the WordPress REST API.

本教程假定您对Vue.js有所了解。 我们将看到如何创建Vue实例,如何使用生命周期挂钩(例如mounted()以及JavaScript Fetch API与WordPress REST API进行交互。

创建一个WordPress插件 (Creating a WordPress Plugin)

In this section, we’ll see how to create a WordPress plugin that registers a shortcode in a few steps.

在本节中,我们将了解如何创建一个WordPress插件,该插件只需几个步骤即可注册一个简码。

在wp-content/plugins创建一个文件夹 (Create a Folder in wp-content/plugins)

Let’s start by creating the back-end part of our plugin. Plugins live inside the wp-content/plugins folder. Navigate to this folder inside your WordPress installation folder and create a sub-folder for your plugin. Let’s call it vueplugin:

让我们从创建插件的后端部分开始。 插件位于wp-content/plugins文件夹中。 导航到WordPress安装文件夹中的该文件夹,然后为您的插件创建一个子文件夹。 我们称之为vueplugin :

cd /var/www/html/wp-content/plugins mkdir vueplugin

Inside your plugin folder, create a vueplugin.php file and add the initial content:

在您的plugin文件夹中,创建一个vueplugin.php文件并添加初始内容:

<?php /* Plugin Name: Latest Posts Description: Latest posts shortcode Version: 1.0 */

These comments are used as meta information for the plugin. In our case, we simply provide a plugin name, description and version.

这些注释用作插件的元信息。 在我们的案例中,我们仅提供插件名称,描述和版本。

If you visit the plugins page in the admin interface you should be able to see your plugin listed:

如果您在管理界面中访问插件页面,则应该可以看到列出的插件:

创建一个简码 (Creating a Shortcode)

Shortcodes are used via WordPress plugins to enable users to add content to posts and pages. To register a shortcode you need to add the following minimal code in your plugin file:

通过WordPress插件使用简码可以使用户向帖子和页面添加内容。 要注册简码,您需要在插件文件中添加以下最少代码:

function handle_shortcode() { return 'My Latest Posts Widget'; } add_shortcode('latestPosts', 'handle_shortcode');

We’re registering a shortcode named latestPosts.

我们正在注册一个名为LatestPosts的简码。

WordPress provides the built-in add_shortcode() function to create the shortcode in your WordPress plugin. The function takes a name as the first parameter and the handler function that processes your shortcode logic and returns an output as a second parameter.

WordPress提供了内置的add_shortcode()函数,可在WordPress插件中创建简码。 该函数以名称作为第一个参数,而处理程序函数则处理您的短码逻辑并返回输出作为第二个参数。

At this point, we’re only returning a static string from our shortcode, but shortcodes are more useful when used to insert dynamic content.

在这一点上,我们只是从我们的简码中返回一个静态字符串,但是简码在用于插入动态内容时更有用。

Now, let’s activate the plugin from the admin interface by clicking on the Activate link below the plugin name:

现在,让我们从管理界面激活插件,方法是单击插件名称下方的“ 激活”链接:

You can use a shortcode by enclosing it in square brackets — that is, [SHORTCODE_NAME]. The text inside the brackets is the name we passed as the first parameter to the add_shortcode() function. It gets replaced by the output returned by the PHP function passed as the second parameter.

您可以通过将短代码括在方括号中来使用它,即[SHORTCODE_NAME] 。 方括号内的文本是我们作为第一个参数传递给add_shortcode()函数的名称。 它被替换为第二个参数PHP函数返回的输出代替。

To test if our shortcode is successfully registered, we can create a new post and add [latestPosts] in the post content:

要测试我们的短代码是否成功注册,我们可以创建一个新帖子,并在帖子内容中添加[latestPosts] :

You should see My Latest Posts Widget sentence rendered:

您应该看到呈现了“ 我的最新帖子”小部件句子:

Now, instead of displaying the static My Latest Posts Widget string, let’s display the latest posts using Vue.js.

现在,我们不显示静态的“ 我的最新帖子”小部件字符串,而是使用Vue.js显示最新的帖子。

将Vue.js与WordPress插件集成 (Integrating Vue.js with a WordPress Plugin)

The Vue docs lists different methods of using Vue.js. The easiest one is using a <script> tag to include the library script, which is also the most straightforward way to integrate Vue.js with WordPress.

Vue文档列出了使用Vue.js的不同方法。 最简单的方法是使用<script>标记包括库脚本,这也是将Vue.js与WordPress集成的最直接的方法。

You can integrate a Vue app with WordPress in a few easy steps:

您可以通过几个简单的步骤将Vue应用程序与WordPress集成:

First, you need to add a DOM element in WordPress (e.g. via a shortcode) where you can mount the Vue app.

首先,您需要在WordPress中添加DOM元素(例如,通过短代码),您可以在其中安装Vue应用。 Next, you need to enqueue the Vue library script.

接下来,您需要排队Vue库脚本。 Finally, you need to create a Vue app inside a separate JavaScript file and enqueue it.

最后,您需要在一个单独JavaScript文件中创建一个Vue应用程序并将其入队。

Unlike the traditional approach of using WordPress, using Vue.js will allow you to add better interactivity and user experience. Instead of needing to constantly reload the current page, users can interact with the page and have the interface dynamically updated. Apps created with Vue.js are called SPAs, or single page applications. But in our case, instead of creating a complete SPA, we’ll only use Vue.js to create a simple widget that can be used to render information in a small part of your page (such as in the sidebar). Think of a widget created with Vue.js as a sort of a small SPA.

与使用WordPress的传统方法不同,使用Vue.js将允许您添加更好的交互性和用户体验。 用户可以与页面进行交互并动态更新界面,而无需经常重新加载当前页面。 用Vue.js创建的应用程序称为SPA,或单页应用程序。 但是在本例中,我们不会使用完整的SPA,而只会使用Vue.js创建一个简单的小部件,该小部件可用于在页面的一小部分(例如侧边栏中)呈现信息。 将用Vue.js创建的小部件想像成一种小型SPA。

Let’s start by enqueueing the Vue library in WordPress. We need to add another function to our plugin which handles the enqueueing of the Vue library:

让我们开始在WordPress中加入Vue库。 我们需要在插件中添加另一个函数来处理Vue库的入队:

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'); } }

We first check if we’re displaying a post that includes our latestPosts shortcode, then we enqueue the Vue script using the wp_enqueue_script() function.

我们首先检查是否显示的帖子包含我们的lastPosts短代码,然后使用wp_enqueue_script()函数使Vue脚本入wp_enqueue_script() 。

You can check if the script is included by visiting your post source code:

您可以通过访问您的帖子源代码来检查脚本是否包括在内:

Next, go back to the handle_shortcode() function and change it to include a <div> where we can render a Vue app:

接下来,返回handle_shortcode()函数并将其更改为包含<div> ,我们可以在其中渲染Vue应用程序:

<div id="mount"></div>

Next, create a latestposts.js file inside your plugin folder and add the following code to create a Vue instance:

接下来,在您的插件文件夹中创建一个latestposts.js文件,并添加以下代码以创建一个Vue实例:

( function() { var vm = new Vue({ el: document.querySelector('#mount'), mounted: function(){ console.log("Hello Vue!"); } }); })();

We create a new Vue instance with the Vue() function, which is the first step to start the Vue application.

我们使用Vue()函数创建一个新的Vue实例,这是启动Vue应用程序的第一步。

When creating the Vue instance, you also need to provide an options object, which allows you to provide different options for building your Vue app.

在创建Vue实例时,还需要提供一个options对象,该对象允许您提供不同的选项来构建Vue应用。

In our example, we use the el property to provide the Vue instance an existing DOM element to mount on. This can be either a CSS selector or an actual HTMLElement. In our case, we use document.querySelector('#mount') to get the HTML element of the <div> with the #mount ID.

在我们的示例中,我们使用el属性为Vue实例提供要安装的现有DOM元素。 这可以是CSS选择器,也可以是实际的HTMLElement 。 在我们的例子中,我们使用document.querySelector('#mount')来获取具有#mount ID的<div>HTML元素。

We also use the mounted property to provide a function that will be called after the instance has been mounted. At this point, we only log a Hello Vue! string on the console.

我们还使用mounted属性来提供一个在实例安装后将被调用的函数。 此时,我们只记录一个Hello Vue! 控制台上的字符串。

You can also browse the full list of the available options in the API reference.

您也可以在API参考中浏览可用选项的完整列表。

Next, just like the Vue library, you need to enqueue this file. Inside the enqueue_scripts() function add the following code:

接下来,就像Vue库一样,您需要使该文件入队。 在enqueue_scripts()函数内部,添加以下代码:

wp_enqueue_script('latest-posts', plugin_dir_url( __FILE__ ) . 'latest-posts.js', [], '1.0', true);

The plugin_dir_url() built-in function is used to get the absolute URL of a file. __FILE__ is a constant that gives you the file-system path to the current PHP file. This will allow us to get the absolute path of the latest-posts.js file without using any hardcoded URLs that could be changed on a different system.

plugin_dir_url()内置函数用于获取文件的绝对URL。 __FILE__是一个常量,为您提供当前PHP文件的文件系统路径。 这将使我们能够获取latest-posts.js文件的绝对路径,而无需使用在其他系统上可能会更改的任何硬编码URL。

At this point you should see the Hello Vue! string on the browser’s console:

此时,您应该看到Hello Vue! 浏览器控制台上的字符串:

And you should also see the latest-posts.js script included in the source code of a post that contains the shortcode.

并且您还应该看到包含短代码的帖子的源代码中包含的latest-posts.js脚本。

Next let’s change the plugin to render the previous My Latest Posts Widget string, but this time from Vue. In your Vue instance, include the template property with whatever HTML code you want to render:

接下来,让我们更改插件以呈现以前的“ 我的最新帖子”小部件字符串,但这一次来自Vue。 在您的Vue实例中,将template属性包含在您要呈现的任何HTML代码中:

var vm = new Vue({ el: document.querySelector('#mount'), template: "<h1>My Latest Posts Widget</h1>", mounted: function(){ console.log("Hello Vue!"); } });

Now, let’s fetch and render the latest posts using the fetch API.

现在,让我们使用访存API来访存并呈现最新帖子。

In the Vue instance, add a data property with a posts array which will hold the fetched posts:

在Vue实例中,添加一个带有posts数组的data属性,该属性将保存获取的帖子:

var vm = new Vue({ el: document.querySelector('#mount'), data: { posts: [] },

Next, let’s include the code to fetch the latest posts in the mounted life-cycle event that gets fired when the component is mounted on the DOM:

接下来,让我们包括代码以获取最新的帖子中安装的生命周期事件时,该组件被安装在DOM是被炒鱿鱼:

var url = '/wp-json/wp/v2/posts?filter[orderby]=date'; fetch(url).then((response)=>{ return response.json() }).then((data)=>{ this.posts = data; })

We call the JavaScript fetch() method which returns a Promise. After successfully resolving the Promise, we assign the data to the posts array.

我们调用JavaScript fetch()方法,该方法返回Promise。 成功解决Promise后,我们将数据分配给posts数组。

Finally, add the template property:

最后,添加模板属性:

template: `<div><h1>My Latest Posts</h1> <div> <p v-for="post in posts"> <a v-bind:href="post.link">{{post.title.rendered}}</span></a> </p> </div> </div>`,

We use the Vue v-for directive to loop through the posts and display the title.rendered and the link properties of each post.

我们使用Vue v-for指令遍历帖子,并显示title.rendered和每个帖子的link属性。

This is a screenshot of the result for me.

这是我的结果的屏幕截图。

In your case, it may look different depending on your active theme and the posts you have in your WordPress website.

对于您而言,根据您的活动主题和WordPress网站中的帖子,外观可能会有所不同。

If you click on the post title you should be taken to the post page.

如果单击帖子标题,则应转到帖子页面。

We can add more features to our widget, such as real-time data fetching, so the user doesn’t need to reload the page to retrieve the latest published posts. We can achieve this by continuously polling the WP-API endpoint using the JavaScript setInterval() method.

我们可以向小部件添加更多功能,例如实时数据获取,因此用户无需重新加载页面即可检索最新发布的帖子。 我们可以通过使用JavaScript setInterval()方法连续轮询WP-API端点来实现此目的。

First, move the code that fetches the posts in its own method:

首先,移动以自己的方法获取帖子的代码:

var vm = new Vue({ /*...*/ methods:{ fetchPosts: function(){ var url = '/wp-json/wp/v2/posts?filter[orderby]=date'; fetch(url).then((response)=>{ return response.json() }).then((data)=>{ this.posts = data; console.log(this.posts); }); } },

We use the methods property of the Vue instance to add custom methods in our Vue instance. You can then access these methods directly on the instance via this.

我们使用Vue实例的methods属性在Vue实例中添加自定义方法。 然后,您可以通过this直接在实例上访问这些方法。

Next, in the mounted() function, add the following code to fetch posts every five seconds:

接下来,在mounted()函数中,添加以下代码以每五秒钟获取一次帖子:

var vm = new Vue({ /*...*/ mounted: function() { console.log("Component is mounted"); this.fetchPosts(); setInterval(function () { this.fetchPosts(); }.bind(this), 5000); }

You can test this by opening the WordPress admin interface in another browser’s tab and adding a new post. You should see your Vue widget updated with a new post without manually refreshing the page.

您可以通过在另一个浏览器的标签中打开WordPress管理界面并添加新帖子来进行测试。 您应该看到Vue小部件已更新为新帖子,而无需手动刷新页面。

结论 (Conclusion)

In this tutorial, we’ve seen how to create a WordPress plugin that makes use of the Vue.js library. We’ve created a shortcode that can be used to display a Vue component in your posts and pages that fetches and displays the latest posts every five seconds. This was achieved via polling the WordPress REST API using the setInterval() method.

在本教程中,我们已经看到了如何创建一个使用Vue.js库的WordPress插件。 我们创建了一个短代码,可用于在您的帖子和页面中显示Vue组件,该组件每五秒钟获取并显示最新的帖子。 这是通过使用setInterval()方法轮询WordPress REST API来实现的。

翻译自: https://www.sitepoint.com/building-a-wordpress-plugin-with-vue/

wordpress vue

相关资源:基于Vue.js与WordPress Rest API构建单页应用详解
最新回复(0)