toRefs和toRef API的使用
# toRefsAPI的使用
<template>
<div>
{{name}}
{{content}}
<button @click="add">点击</button>
</div>
</template>
<script>
import { reactive, toRefs } from "vue";
export default {
setup(props, { attrs, slots, emit }) {
const obj = reactive({ content: 0, name: "XuTao" });
let { content, name } = toRefs(obj);
const add = () => {
content.value++; //todo 这里
};
return{
content,
name,
add
}
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
或者另一种
<template>
<div>
{{ name }}
{{ content }}
<button @click="add">点击</button>
</div>
</template>
<script>
import { reactive, toRefs } from "vue";
export default {
setup(props, { attrs, slots, emit }) {
const obj = reactive({ content: 0, name: "XuTao" });
let { content, name } = toRefs(obj);
const add = () => {
obj.content++; //todo 这里
};
return {
content,
name,
add,
};
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# toRef的使用
<template>
<div>
{{ name }}
{{ content }}
<button @click="add">点击</button>
</div>
</template>
<script>
import { reactive, toRef } from "vue";
export default {
setup(props, { attrs, slots, emit }) {
const obj =reactive( {
name: "XuTao",
content: 0,
});
let content = toRef(obj, "content");
const add = () => {
content.value++ //todo 这里
};
return {
content,
name,
add,
};
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
或者另一种
<template>
<div>
{{ name }}
{{ content }}
<button @click="add">点击</button>
</div>
</template>
<script>
import { reactive, toRef } from "vue";
export default {
setup(props, { attrs, slots, emit }) {
const obj =reactive( {
name: "XuTao",
content: 0,
});
let content = toRef(obj, "content");
const add = () => {
obj.content++ //todo 这里
};
return {
content,
name,
add,
};
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28