Gio*_*dze 3 vue.js vue-component vuex vuejs2
据说composition api解决了mixin带来的命名冲突。
\n这是我在网上找到的关于composition API的内容。
\nexport default {\n setup () {\n const { someVar1, someMethod1 } = useCompFunction1();\n const { someVar2, someMethod2 } = useCompFunction2();\n return {\n someVar1,\n someMethod1,\n someVar2,\n someMethod2\n }\n }\n}\n
Run Code Online (Sandbox Code Playgroud)\n我猜,useCompFunction1()
和useCompFunction2
就像 mixins 一样。在示例中,一切都很好。但是如果useCompFunction1()
和useCompFunction2()
使用具有相同名称的变量,我们在上面的代码中仍然会遇到问题,因为我们无法使用这两个变量。所以,命名冲突当然仍然存在。那为什么说命名冲突可以用 Composition API 解决呢?
更新:
\n我提供的示例,这是我发现应该如何编写可重用代码的代码。
\nimport { ref, computed } from "vue";\n\xe2\x80\xa8\nexport default {\n setup() {\n const count = ref(0);\n const double = computed(() => count.value * 2)\n function increment() {\n count.value++;\n }\n return {\n count,\n double,\n increment\n }\n }\n}\n
Run Code Online (Sandbox Code Playgroud)\n正如您所看到的,它返回带有count
, double
,的变量increment
。它的作用是调用者应该知道它的名称才能使用它。因此,仍然是组合决定了变量的命名。任何想法 ?
和组合函数之间的主要区别mixin
在于,mixin
决定它提供的变量名称,但使用组合函数,您可以根据组合函数提供的结果决定分配的变量名称......
例子:
const { someVar1, someMethod1 } = useCompFunction1();
const { someVar1, someMethod1 } = useCompFunction2();
Run Code Online (Sandbox Code Playgroud)
....大多数 IDE 都会告诉您这是不正确的,因为您声明的变量已经存在...
关键是,里面的变量名是什么并不重要useCompFunction1
,useCompFunction2
因为它们是局部变量。但是要使用它们,您需要声明自己的变量并从组合函数结果中分配它...所以您决定变量名称,而不是您正在使用的“mixin”...
所以,仍然是组合决定了变量的命名
不,是你!
如果您按原样使用结果:
const comp1 = useCompFunction1();
Run Code Online (Sandbox Code Playgroud)
...您将结果与您选择的名称一起使用:
console.log(comp1.count)
Run Code Online (Sandbox Code Playgroud)
但是,如果您选择使用解构,您仍然可以重命名获得的变量:
const { count: count1, double: double1, increment: increment1 } = useCompFunction1();
Run Code Online (Sandbox Code Playgroud)
...现在您可以使用变量count1
,double1
并且increment1
根据您的需要...
您可以重命名变量,例如让我们假设useCompFunction1()
并useCompFunction2()
返回testVar
变量:
const { testVar: testVar1, someMethod1 } = useCompFunction1();
const { testVar: testVar2 } = useCompFunction2();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1454 次 |
最近记录: |