Vue3 +打字稿+合成api-使用.ts文件而不是SFC / .vue文件从外部加载模板内容 与SFC接触... 注意事项

问题描述

我正在尝试使用Composition API defineComponent来定义组件实例。

这取自使用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",template: require("./About.html").default,render() {
        return "this is a test"
      }
    });

添加渲染例程,我得到了渲染的内容

所以似乎defineComponent并没有达到我的期望,因为我使用不正确。它没有定义组件,因为它无法创建渲染例程,除非它在script标签内运行。那么如何将外部加载的模板内容与打字稿模块一起使用?

其他人正在关注:https://github.com/vuejs/rfcs/issues/96

我正在尝试找出实现目标的最佳方法,即将模板和相关代码分离。大概将vue文件渲染成单独的部分,那么什么功能可以实现?

如何正确分离所有组件?

解决方法

templaterender选项是互斥的,因此您应该删除render。您的模板没有出现的原因是template选项需要runtime compiler(由于大多数用户使用预编译的模板,通常不将其作为一种优化措施)。如果尝试在运行时不使用编译器的情况下使用template,则应该看到控制台警告。

要在Vue CLI项目中启用运行时编译器,请设置runtimeCompiler flag

// vue.config.js
module.exports = {
  runtimeCompiler: true,}

要将require的HTML文件转换成template选项的字符串,请像这样使用raw-loader

export default defineComponent({
  template: require('raw-loader!./HelloWorld.html').default
})

与SFC接触...

另一种方法是分别move the <template>,<script>,and <style> parts into .html,.ts,and .css files,然后将它们导入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。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...