第三章 生态篇
详解VCA(组合式API)
VCA提供了一种新的组织和复用逻辑的方式,组合式API允许开发者将相关的逻辑组合在一起,并且更容易在不同组件之间进行共享。
每个使用组合式 API 的组件都必须包含一个 setup() 函数。在 setup() 函数中,你可以执行一些初始化的操作,返回响应式的数据、方法和其他属性供组件使用。
            
            
              html
              
              
            
          
          <template>
    <div></div>
</template>
<script>
    export default{
        setup(){
        }
    }
</script>绑定响应式数据(Reactive Ref)
reactive
用于绑定响应式对象,不能绑定简单数据
            
            
              javascript
              
              
            
          
          export default {
    import {reactive} from 'vue'
    setup(){
        const userInfo = reactive({
            name:'',
            age:''
        })
    }
    return{
        userInfo
    }
}ref
用于绑定响应式数据
            
            
              js
              
              
            
          
          export default {
    import {ref} from 'vue'
    setup(){
        const userInfo = ref({
            name:'',
            age:''
        })
        const userHeigth = ref(178)
    }
    return {
      userInfo,
      userHeight
    }
}VCA中的computed watch
computed
            
            
              js
              
              
            
          
          export default {
    import {reactive,computed} from 'vue' 
    setup(){
        const userInfo = reactive({
            userName:''
        })
        let computedName = computed(()=>userInfo.userName+'1111')
    }
    return{
        userInfo,
        computedName
    }
}watch
计算属性允许我们声明性地计算衍生值。然而在有些情况下,我们需要在状态变化时执行一些'副作用',例如:异步操作
            
            
              js
              
              
            
          
          export default {
    import {reactive,watch} from 'vue' 
    setup(){
        const userInfo = reactive({
            userName:''
        })
        let watchName = watch(userInfo.userName,(oldValue,newValue)=>console.log(newValue,oldValue)
    }
    return{
        userInfo,
        watchName
    }
}VCA中的provide inject
依赖注入
            
            
              js
              
              
            
          
          import {provide,inject,ref} from 'vue'
// 根组件
const testData = ref(true)
provide('testName',testData)
//后代组件
onMounted(()=>{
    const testSonData = inject('testName')
    console.log(testSonData.value)
})Vue 3.2 的setup语法糖
            
            
              html
              
              
            
          
          <script setup></script>