【问题标题】:vue composition api how does it solve naming conflicts?vue composition api如何解决命名冲突?
【发布时间】:2021-02-22 15:19:42
【问题描述】:

据说composition api解决了mixins带来的命名冲突。

这是我在互联网上找到的关于组合 API 的内容。

export default {
  setup () {
    const { someVar1, someMethod1 } = useCompFunction1();
    const { someVar2, someMethod2 } = useCompFunction2();
    return {
      someVar1,
      someMethod1,
      someVar2,
      someMethod2
    }
  }
}

我猜,useCompFunction1()useCompFunction2 就像 mixins。在示例中,一切都很好。但是如果useCompFunction1()useCompFunction2() 使用同名的变量,我们在上面的代码中仍然会遇到问题,因为我们不能同时使用这两个变量。因此,命名冲突当然仍然存在。那为什么说命名冲突是用 Composition API 解决的呢?

更新:

我提供的例子,用它,这是我发现应该如何编写可重用代码的代码。

import { ref, computed } from "vue";


export default {
  setup() {
    const count = ref(0);
    const double = computed(() => count.value * 2)
    function increment() {
      count.value++;
    }
    return {
      count,
      double,
      increment
    }
  }
}

如您所见,它返回带有countdoubleincrement 的变量。它的方式是调用者应该知道它的名称才能使用它。因此,仍然是组合决定了变量的名称。有什么想法吗?

【问题讨论】:

    标签: vue.js vuejs2 vue-component vuex


    【解决方案1】:

    mixin 和组合函数之间的主要区别在于mixin 决定它提供的变量名称,但在组合函数中,决定变量的名称你分配 从合成函数提供的结果中...

    例子:

    const { someVar1, someMethod1 } = useCompFunction1();
    const { someVar1, someMethod1 } = useCompFunction2();
    

    ....大多数 IDE 告诉您这是不正确的,因为您声明了已经存在的变量...

    关键是,useCompFunction1useCompFunction2 中的变量名称是什么并不重要,因为它们是局部变量。但是要使用它们需要声明你自己的变量并从组合函数结果中分配它......所以你决定变量名称,而不是你正在使用的'mixin'......

    更新

    所以,仍然是组合决定了变量的名称

    不,是你!

    如果您按原样使用结果:

    const comp1 = useCompFunction1();
    

    ...您使用您选择的名称的结果:

    console.log(comp1.count)
    

    但是如果你选择使用destructuring,你仍然可以重命名你得到的变量:

    const { count: count1, double: double1, increment: increment1 } = useCompFunction1();
    

    ...现在您可以根据需要使用变量count1double1increment1...

    【讨论】:

      【解决方案2】:

      您可以重命名变量,例如假设useCompFunction1()useCompFunction2() 返回testVar 变量:

      const { testVar: testVar1, someMethod1 } = useCompFunction1();
      const { testVar: testVar2 } = useCompFunction2();
      

      【讨论】:

        猜你喜欢
        • 2015-04-12
        • 1970-01-01
        • 1970-01-01
        • 2019-01-25
        • 2011-01-31
        • 1970-01-01
        • 1970-01-01
        • 2010-12-16
        • 2016-02-20
        相关资源
        最近更新 更多