Ts
Ts description on Vue official website
Ts official website configuration
Why is Vue 3 written in TypeScript? ? ?
A static type system can help prevent many potential runtime errors
Defining Vue Components
For TypeScript to correctly infer the types in Vue Component options, the component needs to be defined using the defineComponent global method:
import {
defineComponent } from 'vue'
const Component = defineComponent({
// 已启用类型推断
})
If you're using single-file components, it's usually written as:
<script lang="ts">
import {
defineComponent } from 'vue'
export default defineComponent({
// 已启用类型推断
})
</script>
When writing the ts code of vue, it is obvious that the code prompt becomes stronger and
used with the Options API
. When performing a split operation on a number, ts immediately detects an error
this.count.split('') // => Property 'split' does not exist on type 'number'
If you have a complex type or interface, you can specify it with a type assertion
interface Book {
title: string
year: number
}
const Component = defineComponent({
data() {
return {
book: {
title: 'Vue 3 Guide',
year: 2020
} as Book
}
}
})
Extended types for globalProperties
Vue 3 provides a globalProperties object to add global properties that can be accessed by any component instance. For example a plugin wants to inject a shared global object or function.
// user defined
import axios from 'axios'
const app = Vue.createApp({
})
app.config.globalProperties.$http = axios
// 验证数据的插件
export default {
install(app, options) {
app.config.globalProperties.$validate = (data: object, rule: object) => {
// 检查对象是否合规
}
}
}
To tell TypeScript about these new properties, we can use module augmentation.
In the above example, we could add the following type declaration:
import axios from 'axios'
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$http: typeof axios
$validate: (data: object, rule: object) => boolean
}
}
We can put these type declarations in the same file, or a project-level *.d.ts file (for example in the src/typings folder that TypeScript will automatically load). For library/plugin authors, this file should be defined in the types property of package.json.
//node_modules/vue-router/package.json
{
"types": "dist/vue-router.d.ts",
}
“types”: “dist/vue-router.d.ts”,
When an input file is specified on the command line, the tsconfig.json file is ignored.
Specify the file path to be detected under the exclude and include of the declaration file tsconfig.json or use the files field;
files can only use relative paths or absolute paths
include/exclude You can use fuzzy matching characters to replace a file with a feature name Click the link below to view the description
There are instructions on the official website, click here to view
The tsconfig.json file can be empty, then all default files will be compiled with default configuration options.
By default all visible "@types" packages will be included during compilation, including all in node_modules
如果指定了typeRoots,只有typeRoots下面的包才会被包含进来
{
"compilerOptions": {
"typeRoots" : ["./typings"]
}
}
如果指定了types,只有被列出来的包才会被包含进来
这个tsconfig.json文件将仅会包含 ./node_modules/@types/node,./node_modules/@types/lodash和./node_modules/@types/express
{
"compilerOptions": {
"types" : ["node", "lodash", "express"]
}
}
By default all visible "@types" packages will be included during compilation. Simply put. /node_modules/@types/, .../node_modules/@types/ and .../.../node_modules/@types/
specify "types" : [ ] to disable automatic import of @types packages
可以继承别的包属性
"extends": "./configs/base",
Commonly used ts error message table
fast
The development server based on the browser's native ES imports uses the browser to parse the imports, compiles and returns on the server side on demand, and completely
skips the concept of packaging. The server is not only
supported by Vue files, but also handles hot updates. , and the speed of hot update will not slow down with the increase of modules
Use vite to create a vue project create-vite-app package
npm init @vitejs/app <project-name>//可以选择创建vue项目 也可以创建react项目
cd <project-name>
npm install
npm run dev
Provided by vue official website
Install vue3 project
Vue Router
Vue cli
blog
Vue3 api document
migration from vue2
应用配置 配置app.config.* globalProperties
app.config.globalProperties.objaaaaaaaaa = {
a:1,b:2}
getCurrentInstance()?.appContext.config.globalProperties
应用API
全局API
createApp
h
defineComponent
defineAsyncComponent
defineCustomElement
resolveDynamicComponent
resolveDirective
withDirectives
createRenderer
nextTick
mergeProps
useCssModule
version
选项
Data
data
props
computed
methods
watch
emits
expose
DOM
template
render
生命周期钩子
beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
activated
deactivated
beforeUnmount
unmounted
errorCaptured
renderTracked
renderTriggered
选项/资源
directives
components
组合
mixins
extends
provide / inject
setup
杂项
name
inheritAttrs
compilerOptions
delimiters
实例property
$data
$props
$el
$options
$parent
$root
$slots
$refs
$attrs
实例方法
$watch
$emit
$forceUpdate
$nextTick
指令
v-text
v-html
v-show
v-if
v-else
v-else-if
v-for
v-on
v-bind
v-model
v-slot
v-pre
v-cloak
v-once
v-memo
v-is
特殊attribute
key
ref
is
内置组件
component
transition
transition-group
keep-alive
slot
teleport
响应性API
响应性基础API
reactive
readonly
isProxy
isReactive
isReadonly
toRaw
markRaw
shallowReactive
shallowReadonly
Refs
ref
unref
toRefs
isRef
customRef
shallowRef
triggerRef
Computed 与 watch
computed
watchEffect
watchPostEffect
watchSyncEffect
watch
侦听单一源
侦听多个源
与watchEffect相同的行为
Effect 作用域API
effectScope
getCurrentScope
onScopeDispose
组合式API
setup
生命周期钩子
Provide / Inject
getCurrentInstance
单文件组件
规范
工具
<script setup>
The use of common methods of vue3
<body>
<div id="app">
<button @click="add">afdas</button>
{
{
count}}
{
{
doubleCount}}
</div>
<script>
const {
reactive, createApp, computed, watch, onMounted, ref , toRefs } = Vue
createApp({
// beforeCreate之前使用
setup(props, context) {
// 响应式数据
const state = reactive({
count: 1,
doubleCount: computed(() => state.count * 2),
})
// 单个原始值响应化
const counter = ref(1)//{_isRef:true,value:1}
setTimeout(() => {
counter.value++ //要修改需要.value
}, 2000);
// 声明一个函数
function add() {
state.count++
}
watch(() => {
console.log('count变了', state.count) // 这里用到了 会被依赖收集 变化就触发了
})
onMounted(() => {
console.log('onMounted')
})
return {
...toRefs(state), add }
}
}).mount('#app')
</script>
</body>
setup
Initialize the setup function between props and beforeCreate
setup(props){
}//porps值基于proxy代理的响应式数据
watchEffect
import {
watchEffect } from '@vue/runtime-core'
setup(props){
//setup内的props不可以解构出title否则 无法监听到title的更新
watchEffect(()=>{
console.log(props.title) // 监听props更新
})
}
The principle of ref setting responsive data: defineProperty listens to value
method one
//ref构建响应式数据 在js中需要.value去访问,在template模板中,只需要对应
<template>
<div>{
{
supNum}}</div> <div>{
{
oppNum}}</div>
</template>
import {
ref } from '@vue/runtime-core'
setup(props){
let supNum = ref(0);
let oppNum = ref(0);
function change(lx){
lx === 0 ? supNum.value++ : oppNum.value++;
}
return {
supNum,
oppNum,
change
}
}
way two
<template>
<div>{
{
state.supNum}}</div> <div>{
{
state.oppNum}}</div>
</template>
import {
ref } from '@vue/runtime-core'
setup(props){
let state = ref({
supNum:0,
oppNum:0
})
function change(lx){
console.log('ok')
lx === 0 ? state.supNum.value++ : state.oppNum.value++;
}
return {
state,
change
}
}
unref parses out the internal data wrapped by ref, no need to use .value to access
let supNum= ref(0)
console.log(unref(supNum))// 0
val = isRef(val) ? val.value : val //isRef检查值是否为一个 ref 对象
toRefs can set each item in the state as responsive and toRef
<template>
<div>{
{
state.supNum}}</div> <div>{
{
state.oppNum}}</div>
</template>
import {
reactive , toRefs } from '@vue/runtime-core'
// Proxy对于数据或者并未初始化的对象成员都可以随意修改值,而且具备响应式的效果
setup(props){
let state = reactive({
supNum:0,
oppNum:0,
arr:[1,2]
})
state.arr[0] = 3
state.name = 'zanlan'
function change(lx){
console.log('ok')
lx === 0 ? state.supNum++ : state.oppNum++;
}
//针对某一个时,则用toRef(state, 'foo')
return {
...toRefs(state),
change
}
}
Reactive sets the principle of responsive data: Proxy monitors the data in depth
<template>
<div>{
{
state.supNum}}</div> <div>{
{
state.oppNum}}</div>
</template>
import {
reactive } from '@vue/runtime-core'
// Proxy对于数据或者并未初始化的对象成员都可以随意修改值,而且具备响应式的效果
setup(props){
let state = reactive({
supNum:0,
oppNum:0
})
state.arr[0] = 3
state.name = 'zanlan'
function change(lx){
console.log('ok')
lx === 0 ? state.supNum++ : state.oppNum++;
}
return {
state,
change
}
}
toRaw
const foo = {
}
const reactiveFoo = reactive(foo)
toRaw(reactiveFoo) === foo // true
readonly set the read-only attribute
readonly(reactive({
count: 0 })).count ++ // 变更副本将失败并导致警告
isProxy checks if the object is a proxy created reactively or readonly.
isProxy(reactive({
count: 0 })) //true
isReactive checks if the object is a reactive proxy created by reactive.
isReactive(reactive({
count: 0 })) //true
isReadonly checks if the object is a readonly proxy created by readonly.
isReadonly(readonly(reactive({
count: 0 }))) // true
computed
Cannot be modified manually
const plusOne = computed(()=>ref(0).value + 1)
plusOne.value // 2
plusOne++ // 报错
If you want to modify the value of the calculated property, you can pass another set function and wrap it in the object
const count = ref(1);
const plusOne = computed({
get:()=>count.value + 1,
set:val => {
count.value = val - 1 }
})
plusOne.value = 1 ;
plusOne.value // 0
life cycle function
beforeCreate setup
created setup
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeDestroy onBeforeUnmount
destroyed onUnmounted
errorCaptured onErrorCaptured
github repository of vuejs
vue source code
addressvue-router source code
addressvue-cli source code
addressvuex source code
addressdevtools source code address
Open Source Project Links
vue-pure-admin
project source code GitHub address
project source code cloud address
project learning address
vue-pure-admin (opens new window) is a free and open source mid-backend template. Developed with the latest vue3 vite2 Element-Plus TypeScript and other mainstream technologies, the out-of-the-box mid-background and front-end solutions can also be used for learning reference.
Installed vscode plugin
Define components
import {
h, defineComponent } from "vue";
var IconifyIconOffline = defineComponent({
name: "IconifyIcon",
components: {
IconifyIcon },//这是另外一个组件
props: {
icon: {
type: String,
default: ""
}
},
render() {
const attrs = this.$attrs;
return h(
IconifyIcon,
{
icon: `${
this.icon}`,
...attrs
},
{
default: () => []
}
);
}
});
const app = createApp(App);
app.component("IconifyIconOffline", IconifyIconOffline);
app.mount("#app");