vue3 composition api 开发实践

目标:利用composition api 实现动态修改gdp数据

compositon api 好处:

  1. 遵循单一职责原则:将相关逻辑组织到单个自定义函数中,便于不同组件的共用,复用性强。
  2. 利用ref、reactive实现响应式数据,以便于数据跟踪
  3. 使用computed实现可读的ref,多个响应式数据组合一个新的响应式数据,用于动态计算。
  4. 利用生命周期钩子函数使用个性化需求

实现步骤

  1. 使用fetch获取数据,将数据转换为响应式数据,并传递给组件
<!--父组件-->
<template>
  <div class="container">
    <Bar1 :Gdp="Gdp"></Bar1>
    <Bar2 :Gdp="Gdp"></Bar2>
  </div>
  <div class="controls">
    <div class="item" v-for="(item,index) in Gdp" :key="index">
      <label>{{ item.country }}</label>
      <input type="number" step="0.001" v-model="item.value" min="0" />
    </div>
  </div>
</template>

<script>
import {ref} from 'vue'
import Bar1 from './components/Bar1.vue'
import Bar2 from './components/Bar2.vue'

export default {
  components: {
    Bar1,
    Bar2
  },
  setup() {
    const gdpRef = ref([]);
    async function getGdp() {
      return  fetch('/api/gdp.json').then((res)=> res.json())
    }
    getGdp().then((data) => {
      gdpRef.value =data
    })
    return {
      Gdp:gdpRef
    }
  },
};
</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
.controls {
  margin: 1em;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
.item {
  margin: 1em;
}
.item label {
  margin: 0 1em;
}
.item input {
  height: 26px;
  font-size: 14px;
}
h1 {
  text-align: center;
}
</style>

  1. 组件1接收数据,由于不能直接将数据渲染到页面,需要将数据进行二次过滤,利用composition的特性,新建useGdp.js(将逻辑代码全部组织到该文件中)便于后期维护及拓展
// hooks函数
import { computed, ref, watch } from "vue";

import gsap from "gsap";

const COLORS = ["#334552", "#B34335", "#6E9FA5", "#A2C3AC", "#C8846C"];

export function useGdp(Gdp, maxValue) {
  const maxGdp = computed(() => {
    return Math.max(...Gdp.value.map((item) => item.value));
  });

  // 当一个或多个响应式需要得到一个新的响应式数据(只读),需要使用computed
  const gdps = computed(() => {
    return Gdp.value.map((item, index) => {
      return {
        ...item,
        color: COLORS[index % Gdp.value.length],
        size: (item.value / maxGdp.value) * maxValue,
      };
    });
  });

  const newGdp = ref([]);

  watch(
    gdps,
    (newValue) => {
      // 实现过渡动画
      for (let i = 0; i < newValue.length; i++) {
        newGdp.value[i] = {
          ...newValue[i],
          size: 0,
          value: 0,
        };
        gsap.to(newGdp.value[i], {
          duration: 1,
          ...newValue[i],
        });
      }
    },
    {
      deep: true,
    }
  );

  return {
    newGdp,
  };
}

  1. useGdp接收组件传的参数(小问题)需要将参数转换为ref,直接传递props.Gdp无效,需要使用computed包裹
<template>
<div class="bar1">
  <div class="item" v-for="(item,index) in newGdp" :key="index">
    <label>{{ item.country }}</label>
    <div class="bar" :style="{background: item.color, width: item.size + 'px'}"></div>
    <div class="value">{{item.value}}万亿</div>
  </div>
</div>
</template>

<script>
import { computed, watch } from 'vue';
import {useGdp} from './../hooks/useGdp'

export default {
    props: ['Gdp'],
    setup (props) {
        const GdpRef = computed(()=>{
            return props.Gdp
        })
        return {
            ...useGdp(GdpRef,400)
        }
    }
}
</script>

<style scoped>
.bar1 {
    width: 500px;
    box-sizing: border-box;
    margin: 3em;
    border-left: 1px solid #333;
  }
  .item {
    display: flex;
    height: 35px;
    line-height: 35px;
    margin: 1em 0;
    position: relative;
  }
  .bar {
    width: 100px;
    height: 100%;
    margin-right: 1em;
    flex: 0 0 auto;
  }
  .item label {
    position: absolute;
    left: -50px;
  }
  .value {
    flex: 0 0 auto;
  }
</style>
  1. useGdp监听数据的变化,对数据进行处理,并返回最终的响应式数据。
  2. 组件解构最终的响应式数据
return {
            ...useGdp(GdpRef,400)
        }

在实际开发中确保返回给页面的参数全部是ref,这样就可以保证统一,维护起来更便捷

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 中的规则(rules)指的是在使用 Vue 3 进行开发时应该遵守的一些最佳实践和约定。以下是一些常见的 Vue 3 规则: 1. 使用 Composition APIVue 3 引入了 Composition API,它提供了一种更灵活和组合性强的方式来组织和重用组件逻辑。建议在新项目中使用 Composition API,以取代传统的 Options API。 2. 使用 TypeScript:Vue 3 对 TypeScript 有更好的支持,使用 TypeScript 可以提供更好的类型检查和编辑器支持,增强代码的可维护性和可读性。 3. 单文件组件:推荐使用单文件组件的方式组织代码,将模板、脚本和样式写在同一个文件中,增加代码的可读性和维护性。 4. 避免使用全局状态:在 Vue 3 中,推荐使用局部状态或使用状态管理库(如 Vuex)来管理状态,避免滥用全局状态。 5. 使用 Teleport:Vue 3 引入了 Teleport 组件,可以方便地将组件渲染到 DOM 结构中的任意位置,避免了一些布局问题。 6. 使用 Fragments:使用 Fragments 可以在不引入额外 DOM 元素的情况下包裹多个子元素,避免因为多余的 DOM 元素导致的布局问题。 7. 优化渲染:使用适当的技巧来优化组件的渲染性能,如使用 v-if 和 v-show 来条件渲染,使用 key 属性来管理列表渲染时的更新。 这些规则可以帮助开发者更好地使用 Vue 3 进行开发,提高代码的质量和可维护性。当然,具体的规则还取决于项目的需求和团队的约定。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值