Vue3.0 + Ts

仅集体应用+繁难了解笔录

环境配置

  1. 根底搭建
npm install -g @vue/cliyarn global add @vue/cli
  1. 创立我的项目
vue create projectName

注:vue2.0 降级到vue3.0

vue add typescript

vue2.0存在许些问题

  1. 组件与组件依赖变大,组件难读取或保护
  2. 不能更好的解决跨组件代码重用

vue3.0 API

  • 1.用于否
可不必状况 Composition Api 来编写组件,也能够不必此api来做组件
  • 2.用此api状况
TypeScript 反对

大型组件,Composition Api 组合可很好的治理状态

跨组件代码重用
  • 3. steup 繁难介绍

setup 是用来配置组件状态的另一种实现。

在setup 中定义的状态,办法要想在模板中应用,必须 return

setup: () => {    const list = ref([])    // 赋值    list.value = []    return {        list    }}

特地留神:

setup 办法是在 [components , props data Methods Computed Lifecycle methods] 之前执行

setup 中无法访问this
  • 4.ref 创立响应式变量
之前 Vue2 中,定义一个响应式变量间接在 data 中 定义即可。

而应用 composition api,咱们得在 setup 中应用 ref 来创立响应式变量,并且得将它返回,能力在页面中应用。

应用示例

import { ref } from 'vue'// 初始化变量const test = ref('默认值')// 赋值 test.value = 'kai shi ....'// 返回(可返回办法)return {    test} 

理论应用栗子

<template>    <div>        <h1>{{test}}</h1>    </div></template><script>import {ref,defineComponent} from 'vue'export default defineComponent({    setup () {        // 定义响应式变量        const test = ref('栗子')                // 输入        console.log(test.value)        // 变量赋值        test.value = '来个新的值'        // 返回变量        return {            test        }    }})</script>
  • 5. 生命周期

    Composition Api 生命周期钩子与vue2.0一样只是多了一个前缀on
vue2.0生命周期    beforeCreate: function() {        console.log('Before Create');    },    created: function() {        console.log('Created');    },    beforeMount: function() {        console.log('Before Mount');    },    mounted: function() {        console.log('Mounted');    },    beforeUpdate: function() {        console.log('Before Update');    },    updated: function() {        console.log('Updated');    },    beforeDestroy: function() {        console.log('Before Destroy');    },    destroyed: function() {        console.log('Destroyed');    }
onMounted 在mounted之前执行
  • 对照表

    | 选项式 API | Hook setup |
    beforeCreate
    created
    beforeMountonBeforeMount
    mountedonMounted
    beforeUpdateonBeforeUpdate
    updatedonUpdated
    beforeUnmountonBeforeUnmount
    unmountedonUnmounted
    errorCapturedonErrorCaptured
    renderTrackedonRenderTracked
    renderTriggeredonRenderTriggered
  • 6.setup 中应用 watch响应式更改

// 引入
import { watch } from 'vue'

// 它有三个参数

  1. 要监听更新的响应式援用或者 getter 函数
  2. 一个回调用来做更新后的操作
  3. 可选配置项
<template>    <div>        {{ count }}    </div></template><script lang="ts">    import { ref, watch } from 'vue'        export default defineComponent({        name: 'Demo',        data() {            return {            }        },        setup(props) {            const count = ref(10)            setTimeout(() =>{                count.value = 20            })            watch(count,(nVal, oVal) =>{                console.log(`新值:${nVal} 旧值:${oVal}`) // 新值:20 旧值:10            })            return {                count,            }        }    })</script>
  • 7.setup 中应用 computed
    computed是从 vue 导入,computed 函数返回一个作为 computed 的第一个参数传递的 getter 类回调的输入的一个只读的响应式援用。为了拜访新创建的计算变量的 value,咱们须要像应用 ref 一样应用 .value property
<template>    <div>        {{ n }}    </div></template><script lang="ts">    import { ref, computed } from 'vue'        export default defineComponent({        name: 'Demo',        data() {            return {            }        },        setup(props) {            const count = ref(10)            setTimeout(() =>{                count.value = 20            })            const n = computed(() =>{                return count.value            })            console.log(n.value)            return {                n,            }        }    })</script>
  • 8.对于setup

    1. 接管两个参数

      props : 父组件传递过去的属性, setup` 函数中 props 是响应式的,它会随着数据更新而更新,并且不能应用 ES6 解构,因为它会不能使 props 为响应式。

      context : 它是一个一般的 对象,它裸露3个组件的· property, context不是响应式,可用es6解构解析

      Attribute(attrs)

      插槽(slots)

      触发事件
<template>    <div>            </div></template><script lang="ts">        export default defineComponent({        name: 'Demo',        props:{            list:{                type: Object,                default: {}            }        },        data() {            return {}        },        // 1        setup(props, context) {            console.log(`props:---- ${JSON.stringify(props)}`)            console.log(`context:---- ${JSON.stringify(context)}`)            // 解构解析            const {attrs, slots, emit} = context        },        // 2         setup(props, {attrs, slots, emit}) {            console.log(`props:---- ${JSON.stringify(props)}`)            console.log(`context:---- ${attrs}`)            console.log(`context:---- ${slots}`)            console.log(`context:---- ${emit}`)        },    })</script>
  1. 组件加载 setup 时注意事项

    在组件执行 setup 时, 组件实例没有被创立,无法访问以下属性:

data

computed

methods

  • 9.跨组件传值

    Vue2 中能够应用 Provide/Inject 跨组件传值,Vue3中也能够。

    setup中应用

    应用 Provide
    1. 用 ref / reactive 创立响应式变量
    2. 用 provide('name', '要传递的响应式变量')
    3. 增加一个更新 响应式变量的事件,这样响应式变量更新, provide 中的变量也跟着更新

父组件

<template> <div>   <Child/>   <button @click="abc">abc</button> </div> </template><script lang="ts">   import { provide, defineComponent, ref, reactive } from "vue";   import Child from './child.vue'   export default defineComponent({       components:{           Child       },       methods: {           abc() {               // 更新time值               this.changeProvide(new Date().getTime()) // 扭转值           },       },       setup() {           const list = ref("父组件");           const testInfo = reactive({               id: 100,               msg: "一个栗子",           });           function changeProvide(t){               testInfo.msg = t           }           provide('list',list)           provide('test',testInfo)           return {changeProvide};       }   })</script>

子组件

<template>   <div>       <h1>{{test.msg}}</h1>       <h1>{{listData}}</h1>   </div></template><script lang="ts">import {provide, defineComponent,ref,reactive, inject} from 'vue'export default defineComponent({   setup () {       const listData = inject('list')       const test = inject('test')       return {listData,test}   }})</script>
  • 10.TypeScript应用
  1. 应用接口束缚类型 interface
<template>   <div>       <ul>           <li>               {{ page }}           </li>       </ul>   </div></template><script lang="ts">interface queryParams{   page: Number,   size: Number,   data: Object,   total:  Number}export default defineComponent({   data() {       return{           page:{               page: 1,               size: 10,               data: {},               total: 10,           } as queryParams       }   }})</script>
  1. reactive应用
    reactive()函数接管一个一般对象,返回一个响应式的数据对象

    <template><div>    <ul>        <li>            {{ list }}        </li>    </ul></div></template><script lang="ts">interface Obj {name: String,id: String,address: String}import { defineComponent, reactive } from "vue"export default defineComponent({setup(props) {    const list = reactive({name:'一个栗子', id: 21, address:'192.168.1.110'}) as Obj    return{        list    }}})</script>
    1. ref与reactive

      ref只能够监听简略数据,reactive能够监听所有数据

    ref批改数据须要应用这样count.value=xxx的模式,而reactive只须要ref批改数据须要应用这样count.属性名=值这样来应用

    reactive在return时候须要toRefs来转换成响应式对象

    reactive 应用<template><div>    <ul>        <li>            {{ page }}            {{ id }}        </li>    </ul></div></template><script lang="ts">import { defineComponent, reactive, toRefs } from "vue"export default defineComponent({setup(props) {    const list = reactive({name:'一个栗子', id: 21, address:'192.168.1.110'}) as Obj    // 扭转值    list.id = 999    return{        ...toRefs(list),    }}})</script>

    ### 对于interface用法

    https://www.cnblogs.com/xch-j...