项目搭建
- vite
npm init vite-app ts-vue3
- vue-cli
npm install -g @vue/cli
vue create ts-vue3
if forget add typescript
vue add typescript
<script lang ="ts">
option api 风格
import { defineComponent, Proptype } form 'vue'
interface Student {
name: string
class:string
age:number
}
const Component = defineComponent({
props: {
success: { type: String },
callback: {
type:Function as PropType<()=>void>},
student:{
type:Object as Proptype,
required:true
}
},
data(){
return {
message: 'Vue3 code Style'
}
},
computed:{
reversendMessage():string {
return this.message.split(' ').reverse().join('')
}
}
})
vue 对 props进行类型验证的时候,就直接用proptype进行强制转换, data中返回的数据也能在不显式定义类型的时候推断出大多类型,computed也只用返回类型的属性就行了。
Composition APi
vue2.0把.vue文件里面的js部分叫做Fuction APi,在3.0里面变为Composition APi
-
reactive & ref reactive():转换响应式对象 ref():转换原始类型为响应式对象
-
区别 reactive 代理初始化一个对象,ref只是一个.value值,在函数中使用都要一直使用.value
-
ref
import { setup,ref } from 'vue'
export default {
setup() {
const year = ref(2020)
const month = ref('11')
month.value = 11
const result = year.value.split('')
}
})
- reactive
import { setup, Reactive } from 'vue'
interface State {
count:number,
class?:number
}
export default {
setup(){
const state: State = reactive({
count:0,
})
}
- watch & computed watch和computed的基本概念与 Vue 2.x 的watch和computed一致,watch可以用于追踪状态变化来执行一些后续操作,computed用于计算属性,用于依赖属性发生变化进行重新计算。computed返回一个只读的包装对象,和普通包装对象一样可以被setup函数返回,这样就可以在模板上下文中使用computed属性。可以接受两个参数,第一个参数返回当前的计算属性值,当传递第二个参数时,computed是可写的