這篇文章主要介紹在 web 前端如何使用 Vue3 對接 js-sdk。
步驟一:引入 JS-SDK
首先在 index.html通過 script 標籤引入 js-sdk。
JS-SDK僅支援非模組化引用方式。引用時,請根據實際填寫版本號碼。
<script src="https://g.alicdn.com/IMM/office-js/1.1.19/aliyun-web-office-sdk.min.js"></script>詳細內容請參見JS-SDK版本。
步驟二:組件 WebOffice.vue 調用 JS-SDK
<template>
<div ref="containerRef" style="width: 100%; height: 100%"></div>
</template>
<script setup>
import { onMounted, ref } from "vue";
const containerRef = ref(null);
onMounted(() => {
init(containerRef.value);
});
const props = defineProps({
getTokenFun: {
type: Function,
required: true
},
refreshTokenFun: {
type: Function,
required: true
},
});
async function init(mount, timeout = 10 * 60 * 1000) {
if(!mount){
console.error("確保掛載節點元素存在。 一般在 onMounted 鉤子中調用。")
}
// 擷取 token
let tokenInfo = await props.getTokenFun();
let ins = window.aliyun.config({
mount,
url: tokenInfo.WebofficeURL,
refreshToken: () => {
// timeout到期時重新整理 token
return props.refreshTokenFun(tokenInfo).then((data) => {
// 儲存供下次 refreshTokenFun 用
Object.assign(tokenInfo, data);
return {
token: tokenInfo.AccessToken,
timeout,
};
});
},
});
ins.setToken({
token: tokenInfo.AccessToken,
timeout,
});
}
</script>步驟三:如何使用 WebOffice.vue 組件
<template>
<!-- container-parent 可以自訂尺寸 -->
<div class="container-parent">
<WebOffice :getTokenFun="getTokenFun" :refreshTokenFun="refreshTokenFun"/>
</div>
</template>
<script setup>
import WebOffice from './WebOffice.vue'
// 定義擷取 token 函數
async function getTokenFun(){
// 調用 web 服務端介面,服務端調用 IMM GenerateWebofficeToken 介面
// 返回格式如下
return {
"RefreshToken": "832e016*******b069eev3",
"RequestId": "652FE412*******350FD7BB4",
"AccessToken": "e20583822*******8905dv3",
"RefreshTokenExpiredTime": "2024-07-11T06:41:25.887690174Z",
"WebofficeURL": "https://office-cn-beijing.imm.aliyuncs.com/office/w/323c0e584a6bed44613ddf9a6bed3f27f0544c5f?_w_tokentype=1",
"AccessTokenExpiredTime": "2024-07-10T07:11:25.887690174Z"
};
}
// 定義重新整理 token 函數
async function refreshTokenFun(){
// 調用 web 服務端介面,服務端調用 IMM RefreshWebofficeToken 介面
// 返回格式如下
return {
"RefreshToken": "832e016e8f*******d7b069eev3",
"RequestId": "652FE41*******9350FD7BB4",
"AccessToken": "e2058382*******8905dv3",
"RefreshTokenExpiredTime": "2024-07-11T06:41:25.887690174Z",
"WebofficeURL": "https://office-cn-beijing.imm.aliyuncs.com/office/w/323c0e584a6bed44613ddf9a6bed3f27f0544c5f?_w_tokentype=1",
"AccessTokenExpiredTime": "2024-07-10T07:11:25.887690174Z"
};
}
</script>
<style>
.container-parent{
width: 800px;
height: 600px;
}
</style>如何擷取token,請看步驟一:服務端封裝介面。