Skip to content

Commit c68e452

Browse files
committed
next round of writing
1 parent a9a8812 commit c68e452

File tree

1 file changed

+57
-1
lines changed

1 file changed

+57
-1
lines changed

src/cookbook/gradual-compositionapi-migration.md

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,60 @@ And it was being used in a modal component in `components/modal.vue`:
5757
</script>
5858
```
5959

60-
We could refactor this by creating a `composables` folder and create `composables/toggle.js` instead. We suggest using a directory named composables so that you can communicate that this is being used slightly differently from a component, it's reusable logic that you can consume.
60+
We could refactor this by creating a `composables` folder and create `composables/useToggle.js` instead. We suggest using a directory named composables so that you can communicate that this is being used slightly differently from a component, it's reusable logic that you can consume.
61+
62+
```js
63+
import { ref, onMounted } from '@vue/composition-api'
64+
65+
export function useToggle() {
66+
const isShowing = ref(false)
67+
68+
function toggleShow() {
69+
isShowing.value = !this.isShowing.value
70+
}
71+
72+
return {
73+
isShowing,
74+
toggleShow
75+
}
76+
}
77+
```
78+
79+
And we can refactor our component as follows:
80+
81+
```html
82+
<template>
83+
<div>
84+
<h3>Let's trigger this here modal!</h3>
85+
86+
<button @click="toggleShow">
87+
<span v-if="isShowing">Hide child</span>
88+
<span v-else>Show child</span>
89+
</button>
90+
91+
<div v-if="isShowing" class="modal">
92+
<h2>Here I am!</h2>
93+
<button @click="toggleShow">Close</button>
94+
</div>
95+
</div>
96+
</template>
97+
```
98+
99+
```js
100+
<script>
101+
import { useToggle } from "@/composables/useToggle.js";
102+
103+
export default {
104+
setup() {
105+
const { isShowing, toggleShow } = useToggle();
106+
107+
return {
108+
isShowing,
109+
toggleShow
110+
};
111+
},
112+
}
113+
</script>
114+
```
115+
116+
Note that the template stays the same, but we've extracted the logic to use in our script section differently. If, from here, we wanted to use `isShowing` in the Options API, we could access it with `this.isShowing`, just as we normally do with a data property, and similarly, we can access `this.toggleShow` like we would a method.

0 commit comments

Comments
 (0)