前言
本篇重点介绍在 TS
的开发环境下使用 Vue
,所以不赘述 TS
的环境搭建,直接基于 ➡️【hello TS】(搭建流程自取)项目进行开发。
另外,vue-cli 也提供一键式集成 typescript
,但本篇的手动配置相信可以带给你更深入的理解。
安装
NPM
$ npm i vue
因为 Vue
自带声明文件,所以不需要额外安装。
创建实例
/*
** src/index.ts
*/
// let hello: string = "hello typescript";
// document.querySelectorAll(".app")[0].innerHTML = hello;
import Vue from "vue";
let app = new Vue({
el: ".app",
data: {
name: "Vue & Typescript" },
template: `<h1>{
{ name }}</h1>`,
});
编译运行,你会发现报错了
vue.runtime.esm.js:623 [Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
(found in <Root>)
“您正在使用 Vue
的仅运行时版本,而模板编译器不可用。可以将模板预编译为渲染函数,也可以使用包含编译器的内部版本。”
runtime-only?运行时版本?
术语
- 完整版:同时包含编译器和运行时的版本。
- 编译器:用来将模板字符串编译成为
JavaScript
渲染函数的代码。 - 运行时:用来创建
Vue
实例、渲染并处理虚拟DOM
等的代码。基本上就是除去编译器的其它一切。
完整版 vs 仅运行时
如果你需要在客户端编译模板 (比如传入一个字符串给 template
选项,或挂载到一个元素上并以其 DOM
内部的 HTML
作为