You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: active-rfcs/0000-function-api.md
+70Lines changed: 70 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -1073,6 +1073,76 @@ Notice how the function-based API cleanly organizes code by logical topic instea
1073
1073
1074
1074
More examples can be found in [this gist](https://gist.github.com/yyx990803/762ec427882a61be3e4affe02f8af555).
1075
1075
1076
+
#### Hybrid Approaches work too
1077
+
1078
+
It is also possible to encapsulate one logic topic in `setup` while otherwise using the Standard API. In this example, mouse-related logic is handled with the Function-based API while the fetching logic is handled with the Standard API.
1079
+
1080
+
_When `setup` is used alongside the Standard API, `setup` runs first and any conflicting properties are overridden by the Standard API._
1081
+
1082
+
```vue
1083
+
<template>
1084
+
<div>
1085
+
<template v-if="isLoading">Loading...</template>
1086
+
<template v-else>
1087
+
<h3>{{ post.title }}</h3>
1088
+
<p>{{ post.body }}</p>
1089
+
</template>
1090
+
<div>Mouse is at {{ x }}, {{ y }}</div>
1091
+
</div>
1092
+
</template>
1093
+
1094
+
<script>
1095
+
import { value, onMounted, onUnmounted } from 'vue'
1096
+
import { fetchPost } from './api'
1097
+
1098
+
function useMouse() {
1099
+
const x = value(0)
1100
+
const y = value(0)
1101
+
const update = e => {
1102
+
x.value = e.pageX
1103
+
y.value = e.pageY
1104
+
}
1105
+
onMounted(() => {
1106
+
window.addEventListener('mousemove', update)
1107
+
})
1108
+
onUnmounted(() => {
1109
+
window.removeEventListener('mousemove', update)
1110
+
})
1111
+
return { x, y }
1112
+
}
1113
+
1114
+
export default {
1115
+
props: {
1116
+
id: Number
1117
+
},
1118
+
setup(props) {
1119
+
return {
1120
+
...useMouse()
1121
+
}
1122
+
},
1123
+
data() {
1124
+
return {
1125
+
isLoading: true,
1126
+
post: null,
1127
+
}
1128
+
},
1129
+
mounted() {
1130
+
this.fetchPost()
1131
+
},
1132
+
watch: {
1133
+
id: 'fetchPost'
1134
+
},
1135
+
methods: {
1136
+
async fetchPost() {
1137
+
this.isLoading = true
1138
+
this.post = await fetchPost(this.id)
1139
+
this.isLoading = false
1140
+
}
1141
+
}
1142
+
}
1143
+
</script>
1144
+
```
1145
+
1076
1146
## Comparison with React Hooks
1077
1147
1078
1148
The function based API provides the same level of logic composition capabilities as React Hooks, but with some important differences. Unlike React hooks, the `setup()` function is called only once. This means code using Vue's function APIs are:
0 commit comments