组合式API与选项式API

组合式API与选项式API

选项式API

  • 关注点:一个一个选项上(配置项)
  • 特点:分散
  • 比如data、methods、computed、watch 选项式API的关注点没有在功能上,没有这种一个一个独立的功能概念
<template>

</template>

<script>
  export default {
      
      
    data() {
      
      
      return {
      
      
        // 功能1的data
        // 功能2的data
        // 功能3的data
      }
    },
    methods: {
      
      
      // 功能1的methods
      // 功能2的methods
      // 功能3的methods
    },
    computed: {
      
      
      // 功能1的computed
      // 功能2的computed
      // 功能3的computed
    },
    watch: {
      
      
      // 功能1的watch
      // 功能2的watch
      // 功能3的watch
    }
  }
</script>

可以看出,实现功能的代码非常分散,维护成本高,比较乱

组合式API

组合式API + hooks 关注点在功能上

  • hook1.js:
// 一个钩子就是一个独立的功能
// 这一次的关注点在功能上。
export default function() {
    
    
  // 功能1的data
  // 功能1的methods
  // 功能1的watch
  // 功能1的computed
  // ....
}
<template>

</template>

<script>
  import hook1 from "./hook1";
  import hook2 from "./hook2";
  export default {
      
      
    setup() {
      
      
      hook1() // 需要使用功能1,就调用hook1的钩子
      hook2() // 需要使用功能2,就调用hook2的钩子
    }
  }
</script>
涉及内容

VUE3、组合式API、选项式API、hooks

猜你喜欢

转载自blog.csdn.net/MCCLS/article/details/131815230