[英]Vue3 + typescript + composition api - loading template content externally using .ts files not SFCs/.vue files
我正在嘗試使用defineComponent
API 來定義組件來定義組件實例。
這取自使用vue create myapp
命令創建的起始項目。 該腳本已放入 about.ts 文件中,來自 About.vue 文件的模板內容放入了 About.html 文件(可能應該是 .vue 文件,因為它不是真正的 html)。
import { defineComponent } from "vue";
export default defineComponent({
name: "About",
props: {
msg: String
},
template: require("./About.html").default
});
這是在about.ts
中舉行的。
在我的router/index.ts
中使用,如下所示:
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import Home from "@/views/Home.vue";
import About from "@/views/About"
const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/about",
name: "About",
component: About
}
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
});
export default router;
它不渲染任何東西。 查看我的“關於”視圖和“主頁”視圖之間的區別,看起來唯一的區別是缺少渲染例程(當您使用 .vue 文件創建組件時會出現這種情況。
所以讓我們定義一個:
import { defineComponent } from "vue";
export default defineComponent({
name: "About",
props: {
msg: String
},
template: require("./About.html").default,
render() {
return "this is a test"
}
});
添加渲染例程,我得到渲染的內容
所以看起來 defineComponent 沒有做我期望的事情,因為我使用不正確。 它沒有定義組件,因為它無法創建渲染例程,除非它在腳本標簽內運行。 那么如何將外部加載的模板內容與打字稿模塊一起使用?
其他人在看: https ://github.com/vuejs/rfcs/issues/96
我正在嘗試找出實現目標的最佳方法,即分離模板和相關代碼。 大概 vue 文件被渲染成單獨的部分,那么什么功能可以實現呢?
您如何正確地將所有組件分開?
template
和render
選項是互斥的,所以你應該刪除render
。 您的模板沒有出現的原因是template
選項需要運行時編譯器(它通常被排除在優化之外,因為大多數用戶使用預編譯模板)。 如果您嘗試在沒有編譯器的情況下在運行時使用template
,您應該會看到控制台警告。
要在 Vue CLI 項目中啟用運行時編譯器,請設置runtimeCompiler
標志:
// vue.config.js
module.exports = {
runtimeCompiler: true,
}
require
HTML 文件轉換為template
選項的字符串,請使用raw-loader
,如下所示:
export default defineComponent({
template: require('raw-loader!./HelloWorld.html').default
})
另一種方法是將<template>
、 <script>
和<style>
部分分別移動到.html
、 .ts
和.css
文件中,然后將它們導入 SFC:
<!-- HelloWorld.vue -->
<template src="./HelloWorld.html"></template>
<script src="./HelloWorld.ts" lang="ts"></script>
<style src="./HelloWorld.css"></style>
該應用程序仍將照常導入組件:
<script>
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
像這樣拆分文件會花費Vetur提供的 IDE 支持。 例如,在 HTML 文件中,您不會獲得腳本文件中聲明的道具的 IntelliSense。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.