承接上文,我們將常用選項(xiàng)中的兩個(gè)功能給實(shí)現(xiàn)了,這一節(jié),我們將對(duì) JS 資源進(jìn)行打包,最終產(chǎn)物只有一個(gè) JS 文件和一個(gè) CSS 文件,可以極大的提升網(wǎng)頁(yè)加載速度,減少依賴。
打包后的文件中,就包含了 vue3 和 Axios 的代碼內(nèi)容,不必通過(guò)URL 引入 vue3 的所有功能了。而且,在打包之前,還能對(duì)各種選項(xiàng)進(jìn)行自定義的驗(yàn)證,還能使用各種前端框架,對(duì)選項(xiàng)進(jìn)行美化。
更重要的是,使用打包后的文件,可以明顯減少頁(yè)面卡頓。
- 本系列代碼分享在 GitHub 中,希望能幫助大家理解
- https://github.com/muze-page/vue-spa
本節(jié)流程

準(zhǔn)備打包環(huán)境
我們使用 Vite 進(jìn)行打包,您需要提前安裝 node 環(huán)境,
創(chuàng)建環(huán)境
使用 VS Code 打開我們的vue-spa文件夾,通過(guò)Ctrl+~ 打開終端,輸入以下命令創(chuàng)建 Vue 3 項(xiàng)目
npm create vite@latest vites -- --template vue
稍等片刻后,分別執(zhí)行以下幾個(gè)命令
cd vites
npm install
npm run dev
會(huì)提示一個(gè)網(wǎng)址,

我們將其在瀏覽器中打開,即可看到如下顯示

我們同時(shí)按下 Ctrl+c 暫停當(dāng)前運(yùn)行,回到控制臺(tái)中。
安裝Axios
在控制臺(tái)中輸入以下命令,安裝 Axios
npm install axios
安裝完成后,打開vites文件夾下的 package.json 文件即可看到如下提示

即代表您安裝成功了。
重寫index.js
現(xiàn)在,我們需要重寫 index.js 文件,我們?cè)?vites/src/components/ 文件夾下,新建文件 Option.vue
文件。寫入以下內(nèi)容
<script setup>
import { reactive, onMounted } from "vue";
import axios from "axios";
const siteData = dataLocal.data;
//存儲(chǔ)獲取的值
const getData = reactive({
//存儲(chǔ)獲取的媒體庫(kù)值
mediaList: [],
});
//存儲(chǔ)選項(xiàng)值
const datas = reactive({
dataOne: "",
dataTwo: "",
dataName: [],
dataImage: "",
dataSelectedImage: "",
});
//獲取數(shù)據(jù)
const get_option = () => {
axios
.post(dataLocal.route + "pf/v1/get_option", datas, {
headers: {
"X-WP-Nonce": dataLocal.nonce,
"Content-Type": "application/json",
},
})
.then((response) => {
const data = response.data;
datas.dataOne = data.dataOne;
datas.dataTwo = data.dataTwo;
datas.dataName = data.dataName;
datas.dataImage = data.dataImage;
datas.dataSelectedImage = data.dataSelectedImage;
})
.catch((error) => {
window.alert("連接服務(wù)器失敗或后臺(tái)讀取出錯(cuò)!數(shù)據(jù)讀取失敗");
console.log(error);
});
};
//保存數(shù)據(jù)
const update_option = () => {
console.log(datas);
axios
.post(dataLocal.route + "pf/v1/update_option", datas, {
headers: {
"X-WP-Nonce": dataLocal.nonce,
},
})
.then((response) => {
alert("保存成功");
})
.catch((error) => {
alert("保存失敗");
console.log(error);
});
};
//上傳圖片
const upload_img = (file) => {
const formData = new FormData();
formData.append("file", file);
return axios
.post(dataLocal.route + "wp/v2/media", formData, {
headers: {
"X-WP-Nonce": dataLocal.nonce,
"Content-Type": "multipart/form-data",
},
})
.then((response) => {
// 圖片上傳成功后的處理邏輯
const data = response.data;
//返回圖片URL
return data.source_url;
})
.catch((error) => {
console.error(error);
// 圖片上傳失敗后的處理邏輯
});
};
//處理圖片上傳事件
const update_img = (event) => {
const file = event.target.files[0];
upload_img(file).then((url) => {
//將拿到的圖片URL傳給圖片變量
datas.dataImage = url;
});
};
//清空選擇圖片
const clear_img = () => {
datas.dataImage = "";
};
//獲取媒體庫(kù)圖片
const getMediaList = () => {
axios
.get(dataLocal.route + "wp/v2/media")
.then((response) => {
getData.mediaList = response.data;
})
.catch((error) => {
console.error(error);
});
};
//從媒體庫(kù)選中圖片
const selectImage = (imageUrl) => {
datas.dataSelectedImage = imageUrl;
};
//頁(yè)面初始加載
onMounted(() => {
//獲取選項(xiàng)值
get_option();
});
</script>
<template>
<!--兩個(gè)輸入框-->
文本框1:<input type="text" v-model="datas.dataOne" /><br />
文本框2:<input type="text" v-model="datas.dataTwo" />
<hr />
<!--用戶選擇-->
用戶選擇:<select v-model="datas.dataName" multiple>
<option v-for="option in siteData.user" :key="option.id" :value="option.id">
{{ option.name }}
</option>
</select>
<p>你選擇了:{{ datas.dataName }}</p>
<br />
按住command(control)按鍵即可進(jìn)行多選
<hr />
<!--圖片上傳-->
<input type="file" @change.native="update_img" /><br />
<button type="button" @click="clear_img">清理</button><br />
<img :src="datas.dataImage" v-if="datas.dataImage" />
<hr />
<!--獲取媒體庫(kù)圖片-->
<button @click="getMediaList">獲取媒體庫(kù)圖片</button>
<div class="box">
<div v-for="media in getData.mediaList" :key="media.id" style="float: left">
<img :src="media.source_url" />
<button @click="selectImage(media.source_url)">選擇</button>
</div>
</div>
<h2>{{ datas.dataSelectedImage ? "已" : "未" }}選擇圖片</h2>
<img :src="datas.dataSelectedImage" v-if="datas.dataSelectedImage" />
<hr />
<button class="button button-primary" @click="update_option">保存</button>
</template>
<style scoped>
img {
max-width: 150px;
height: auto;
vertical-align: top;
}
.box {
max-width: 800px;
display: flex;
margin: 1em 0;
}
</style>
這里,對(duì)原有寫法在語(yǔ)法糖 setup 的幫助下,進(jìn)行了部分重寫,再抽離了部分CSS樣式,使得整體的代碼更加健壯和容易維護(hù)了。
當(dāng)然,還有更多方法可以優(yōu)化,為了便于講解,這里不再贅述。
修改 App.js
/vites/src/
模塊制作好了,我們?cè)?App.vue 文件中導(dǎo)入,寫入以下內(nèi)容
<script setup>
//import HelloWorld from "./components/HelloWorld.vue";
import Option from "./components/Option.vue";
</script>
<template>
<Option></Option>
</template>
<style scoped></style>
將我們寫的組件展示出來(lái)
修改main.js
/vites/src/
在之前的章節(jié)中,我們提前準(zhǔn)備的ID 是 vuespa
,所以,需要修改下此文件為以下內(nèi)容
import { createApp } from 'vue'
//import './style.css'
import App from './App.vue'
createApp(App).mount('#vuespa')
在這里,我還把默認(rèn)的 CSS 樣式給注釋了
修改 vite.config.js
/vites/src/
為了讓打包后的文件名與我們?cè)械奈募3忠恢拢覀冃枰薷南麓虬?xì)節(jié),替換該文件為以下內(nèi)容
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
build: {
rollupOptions: {
output: {
// 指定 chunk 文件名(含導(dǎo)出的代碼)
//chunkFileNames: 'js/[name].js',
// 指定靜態(tài)資源文件名(不含導(dǎo)出的代碼)
//assetFileNames: 'assets/[name].[ext]',
entryFileNames: "index.js",
assetFileNames: "[name][extname]",
chunkFileNames: "[name].js",
},
},
},
});
這樣,打包后就會(huì)產(chǎn)出 index.js 和 index.css 文件了,而不會(huì)攜帶別的字符。
wordpress 會(huì)緩存部分 JS 資源,記得在 vue-spa.php 文件中修改 vuespa_load_vues() 函數(shù)的版本號(hào)
打包
打包的過(guò)程,就是優(yōu)化整合各代碼的過(guò)程,我們定位到 vites 文件夾下,輸入以下代碼進(jìn)行打包。
npm run build
完成后,如下所示

我們可以在如下位置找到打包后的文件
/vites/dist/
導(dǎo)入
有了打包好的 JS 文件和 CSS 文件,現(xiàn)在,我們將其在菜單中導(dǎo)入,修改 vue-spa.php
文件中的函數(shù)vuespa_load_vues()
為以下內(nèi)容
//載入所需 JS 和 CSS 資源 并傳遞數(shù)據(jù)
function vuespa_load_vues($hook)
{
//判斷當(dāng)前頁(yè)面是否是指定頁(yè)面,是則繼續(xù)加載
if ('toplevel_page_vuespa_id' != $hook) {
return;
}
//版本號(hào)
$ver = '55';
//加載到頁(yè)面頂部
wp_enqueue_style('vite', plugin_dir_url(__FILE__) . 'vites/dist/index.css', array(), $ver, false);
//加載到頁(yè)面底部
wp_enqueue_script('vite', plugin_dir_url(__FILE__) . 'vites/dist/index.js', array(), $ver, true);
$pf_api_translation_array = array(
'route' => esc_url_raw(rest_url()), //路由
'nonce' => wp_create_nonce('wp_rest'), //驗(yàn)證標(biāo)記
'data' => vuespa_data(), //自定義數(shù)據(jù)
);
wp_localize_script('vite', 'dataLocal', $pf_api_translation_array); //傳給vite項(xiàng)目
}
//樣式加載到后臺(tái)
add_action('admin_enqueue_scripts', 'vuespa_load_vues');
這里,我們無(wú)需手動(dòng)載入 vue.js 和 Axios.js 文件了,打包后的 index.js 文件中,都準(zhǔn)備好了,減少了不必要的資源開銷。
添加type屬性
注意,因?yàn)槲覀兇虬蟮?index.js 文件,是一個(gè)模塊,需要給其添加一個(gè) type 屬性才能正常生效。
我們?cè)?vue-spa.php
文件底部,添加以下代碼,給導(dǎo)入的 index.js 添加type屬性,
//模塊導(dǎo)入
function add_type_attribute_to_script($tag, $handle)
{
// 在這里判斷需要添加 type 屬性的 JS 文件,比如文件名包含 xxx.js
if (strpos($tag, 'index.js') !== false) {
// 在 script 標(biāo)簽中添加 type 屬性
$tag = str_replace('<script', '<script type="module"', $tag);
}
return $tag;
}
add_filter('script_loader_tag', 'add_type_attribute_to_script', 10, 2);
效果如下:
//使用函數(shù)前
<script src='<http://localhost:10004/wp-content/plugins/vue-spa/vites/dist/index.js?ver=53>' id='vite-js'></script>
//使用函數(shù)后
<script type="module" src='<http://localhost:10004/wp-content/plugins/vue-spa/vites/dist/index.js?ver=53>' id='vite-js'></script>
補(bǔ)充
若您需要在本地進(jìn)行開發(fā)和預(yù)覽,您可能需要以下幾個(gè)知識(shí)
修改 index.html
/vites/
修改文件為以下內(nèi)容,
<body>
<div id="vuespa"></div>
<script type="module" src="/src/main.js"></script>
</body>
拿不到傳來(lái)的 dataLocal
dataLocal 的值是外部傳來(lái)的,vite 并不知道,您可以通過(guò)臨時(shí)添加以下內(nèi)容,進(jìn)行模仿,但記得,在打包前進(jìn)行注釋。
const dataLocal = {
route: "http://localhost:5173/wp-json/",
nonce: "asdf",
data: {
user: [
{ id: 1, name: "111" },
{ id: 2, name: "222" },
],
},
};
vue-spa.php完整代碼
<?php
/*
Plugin Name: Vue - SPA
Plugin URI: http://m.kartiktrivedi.com
Description: 將vue構(gòu)建的頁(yè)面嵌入WordPress 中并產(chǎn)生交互
Author: Muze
Author URI: http://m.kartiktrivedi.com
Version: 1.0.0
*/
//接口
require_once plugin_dir_path(__FILE__) . 'interface.php';
//創(chuàng)建一個(gè)菜單
function vuespa_create_menu_page()
{
add_menu_page(
'VueSpa選項(xiàng)', // 此菜單對(duì)應(yīng)頁(yè)面上顯示的標(biāo)題
'VueSpa', // 要為此實(shí)際菜單項(xiàng)顯示的文本
'administrator', // 哪種類型的用戶可以看到此菜單
'vuespa_id', // 此菜單項(xiàng)的唯一ID(即段塞)
'vuespa_menu_page_display', // 呈現(xiàn)此頁(yè)面的菜單時(shí)要調(diào)用的函數(shù)的名稱 'vuespa_menu_page_display'
'dashicons-admin-customizer', //圖標(biāo) - 默認(rèn)圖標(biāo)
'500.1', //位置
);
} // end vuespa_create_menu_page
add_action('admin_menu', 'vuespa_create_menu_page');
//菜單回調(diào) - 展示的內(nèi)容
function vuespa_menu_page_display()
{
?>
<!--在默認(rèn)WordPress“包裝”容器中創(chuàng)建標(biāo)題-->
<div class="wrap">
<!--標(biāo)題-->
<h2><?php echo esc_html(get_admin_page_title()); ?></h2>
<!--提供Vue掛載點(diǎn)-->
<div id="vuespa">此內(nèi)容將在掛載Vue后被替換{{data}}</div>
</div>
<?php
//展示準(zhǔn)備的數(shù)據(jù)
echo "<pre>";
print_r(vuespa_data());
echo "</pre>";
echo "<h3>調(diào)用選項(xiàng)值</h3>";
echo get_option('dataOne');
echo "<br/>";
echo get_option('dataTwo');
echo "<br/>";
print_r(get_option('dataName'));
echo "<br/>";
echo get_option('dataImage');
echo "<br/>";
echo get_option('dataSelectedImage');
} // vuespa_menu_page_display
//載入所需 JS 和 CSS 資源 并傳遞數(shù)據(jù)
function vuespa_load_vues($hook)
{
//判斷當(dāng)前頁(yè)面是否是指定頁(yè)面,是則繼續(xù)加載
if ('toplevel_page_vuespa_id' != $hook) {
return;
}
//版本號(hào)
$ver = '53';
//加載到頁(yè)面頂部
wp_enqueue_style('vite', plugin_dir_url(__FILE__) . 'vites/dist/index.css', array(), $ver, false);
//加載到頁(yè)面底部
wp_enqueue_script('vite', plugin_dir_url(__FILE__) . 'vites/dist/index.js', array(), $ver, true);
$pf_api_translation_array = array(
'route' => esc_url_raw(rest_url()), //路由
'nonce' => wp_create_nonce('wp_rest'), //驗(yàn)證標(biāo)記
'data' => vuespa_data(), //自定義數(shù)據(jù)
);
wp_localize_script('vite', 'dataLocal', $pf_api_translation_array); //傳給vite項(xiàng)目
}
//樣式加載到后臺(tái)
add_action('admin_enqueue_scripts', 'vuespa_load_vues');
//準(zhǔn)備待傳輸?shù)臄?shù)據(jù)
function vuespa_data()
{
$person = [
"str" => "Hello, world! - Npcink",
"num" => 25,
"city" => [1, 2, 3, 4, 5],
"user" => vuespa_get_user_meat(),
];
return $person;
}
//整理并提供用戶信息
function vuespa_get_user_meat()
{
//獲取所有角色
$editable_roles = wp_roles()->roles;
$roles = array_keys($editable_roles);
//獲取除了'subscriber'(訂閱者)角色之外的所有角色的用戶數(shù)據(jù)
$subscriber_key = array_search('subscriber', $roles, true);
if (false !== $subscriber_key) {
$roles = array_slice($roles, 0, $subscriber_key);
}
$users = get_users(array('role__in' => $roles));
//轉(zhuǎn)為關(guān)聯(lián)數(shù)組
$user_data = array_map(function ($user) {
return [
'id' => $user->ID,
'name' => $user->display_name,
];
}, $users);
return $user_data;
}
//模塊導(dǎo)入
function add_type_attribute_to_script($tag, $handle)
{
// 在這里判斷需要添加 type 屬性的 JS 文件,比如文件名包含 xxx.js
if (strpos($tag, 'index.js') !== false) {
// 在 script 標(biāo)簽中添加 type 屬性
$tag = str_replace('<script', '<script type="module"', $tag);
}
return $tag;
}
add_filter('script_loader_tag', 'add_type_attribute_to_script', 10, 2);
總結(jié)
本章節(jié)中,我們使用 Vite 對(duì) index.js 文件進(jìn)行了打包等處理,基于現(xiàn)在的 Node 生態(tài),您還可以
- 使用 mockjs 提供攔截,更方便的進(jìn)行本地開發(fā)
- 使用現(xiàn)成的前端框架提升開發(fā)效率,例如 Element Plus
- 使用 Pinia 進(jìn)行數(shù)據(jù)的統(tǒng)一管理
- 使用第三方庫(kù),實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)
- 使用TS約束變量類型,提升代碼健壯性
因篇幅原因,此處不再贅述。
下面是我使用 Element Plus 做出的下拉選項(xiàng)卡,比瀏覽器默認(rèn)的好用多了

如果您能堅(jiān)持看到這里,相信您也會(huì)有所收獲,希望您能基于此教程,做出更多有趣和實(shí)用的代碼來(lái)。
最新文章
- 后續(xù)文章持續(xù)撰寫中,點(diǎn)個(gè)關(guān)注,獲取平臺(tái)最新文章推送。
- 技術(shù)有限,還望諸位協(xié)助勘誤,于評(píng)論區(qū)指出,
- 常一文多發(fā),最新勘定和增補(bǔ)文章于下方鏈接給出
- http://m.kartiktrivedi.com/277313.html