admin管理员组文章数量:1363337
The following reactive
object has a variable and also a function declared inside of it:
const state = reactive({
names: [] as string[],
add(name: string): void {
this.names.push(name);
},
});
So that I can call it directly:
state.add('foo');
The official docs say nothing about having functions inside reactive
.
Is there any problem with this approach?
The following reactive
object has a variable and also a function declared inside of it:
const state = reactive({
names: [] as string[],
add(name: string): void {
this.names.push(name);
},
});
So that I can call it directly:
state.add('foo');
The official docs say nothing about having functions inside reactive
.
Is there any problem with this approach?
Share edited 20 hours ago rodrigocfd asked 23 hours ago rodrigocfdrodrigocfd 8,1278 gold badges46 silver badges79 bronze badges 1- 1 It's perfectly normal. There would be a problem if "this" were bound to wrong context – Estus Flask Commented 23 hours ago
1 Answer
Reset to default 0Yes! You can define a function inside a reactive
object, Vue reactive is a proxy
that tracks property access and updates, so whenever you update the names
array, the change will be accessible.
Be careful with this
keyword, with normal functions add() {...}
dynamically bind this
to the reactive object, but arrow functions add: () => {...}
do not have their own this
, for more details about this
see https://stackoverflow/a/134149/29157031
Here is an example:
<script setup lang="ts">
import { reactive } from 'vue'
const state = reactive({
names: [] as string[],
add(name: string): void {
this.names.push(name);
},
add_2: (name: string): void => {
// this.names.push(name); // ERROR: Cannot read properties of undefined (reading 'names')
state.names.push(name);
},
});
setTimeout(()=>{
state.add('1');
state.add_2('2');
}, 2000)
</script>
<template>
<button @click="()=>state.add('John')">Add Name 1</button>
<button @click="()=>state.add_2('John')">Add Name 2</button>
<p>Names: {{ state.names }}</p>
<p>Count: {{ state.names.length }}</p>
</template>
see this vue playground to test the code
本文标签: javascriptCan I declare a function inside a reactive object in Vue 3Stack Overflow
版权声明:本文标题:javascript - Can I declare a function inside a reactive object in Vue 3? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743771865a2536267.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论