vue-hooks的理解与使用

vue的hooks和mixins功能相似,但又比mixins具有以下几个优势:

  • 允许hooks间相互传递值
  • 组件之间重用状态逻辑
  • 明确指出逻辑来自哪里

demo源码示意:

hook1:

import { useData, useMounted } from 'vue-hooks';
 
export function windowwidth() {
  const data = useData({
    width: 0
  })
 
  useMounted(() => {
    data.width = window.innerWidth
  })
 
  // this is something we can consume with the other hook
  return {
    data
  }
}

hook2:

// the data comes from the other hook
export function logolettering(data) {
  useMounted(function () {
    // this is the width that we stored in data from the previous hook
    if (data.data.width > 1200) {
      // we can use refs if they are called in the useMounted hook
      const logoname = this.$refs.logoname;
      Splitting({ target: logoname, by: "chars" });
 
      TweenMax.staggerFromTo(".char", 5,
        {
          opacity: 0,
          transformOrigin: "50% 50% -30px",
          cycle: {
            color: ["red", "purple", "teal"],
            rotationY(i) {
              return i * 50
            }
          }
        },
        ...

在组件内部,我们可以将 hook1 作为参数传递给 hook2:

<script>
import { logolettering } from "./../hooks/logolettering.js";
import { windowwidth } from "./../hooks/windowwidth.js";
 
export default {
  hooks() {
    logolettering(windowwidth());
  }
};
</script>

更多vue-hooks使用demo链接

你可能感兴趣的:(vue,vue)