[Drag&Drop] WordPress嵌入SPA单页面测试

背景

有个用vue写的demo想嵌在wp blog中显示。

效果

以下是一个用vue.js实现的drag&drop demo页面。

调研

查到了两种方式,本质都是将SPA打包之后的dist文件上传到wp-content目录下,然后通过iframe嵌入。

Custom Page Template方式

一种是在theme路径下添加新的template.php文件,然后在新建页面时的”Page Attributes”选择。缺点是如果theme本身不支持就没办法生效。

PHP
// template.php

<?php
/*
 * Template Name: Vue Page Template
 * Description: Template for embedding a Vue.js application.
 */

// Prevent direct access to this file
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

get_header(); // Load the header template
?>

<div id="vue-app">
    <!-- Embedding the Vue.js application using an iframe -->
    <iframe src="/path/to/vue-app/index.html" frameborder="0" width="100%" height="600"></iframe>
</div>

<?php
get_footer(); // Load the footer template
PHP

ShortCode方式

「Shortcodes are a powerful feature in WordPress that allow you to add dynamic content or functionality to your posts and pages using a simple shortcode tag.」这是一种适用于任何theme的方法。

首先在theme目录下的functions.php文件中添加shortcode(可以加在最外层的任何位置)

PHP
function vue_app_shortcode() {
    // Embedding the Vue.js application using an iframe
    return '<iframe src="/path/to/vue-app/index.html" frameborder="0" width="100%" height="600"></iframe>';
}
add_shortcode( 'vue_app', 'vue_app_shortcode' );
PHP

然后在新建post/page的时候就可以直接在编辑页面输入对应的shortcode来插入iframe。

XML
Welcome to our Vue Application Page!

[vue_app]
XML

注意点

  1. 打包之后的dist需要放在/wp-content之下,iframe的路径也是由‘/wp-content’开头的,否则会找不到页面。
  2. 编辑模式下[vue_app]会解析为代码,[[vue_app]]会解析为正常文本。

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *