|
1 | 1 | <script lang="ts">
|
2 |
| -import { computed, defineComponent, nextTick, onBeforeUnmount, ref, watch } from 'vue' |
| 2 | +import { computed, defineComponent, getCurrentInstance, nextTick, onBeforeUnmount, onMounted, onUnmounted, ref, watch } from 'vue' |
3 | 3 |
|
4 | 4 | import { IN_BROWSER } from '../util'
|
5 | 5 | import { useStack } from '../composables/stack'
|
@@ -97,6 +97,15 @@ export default defineComponent({
|
97 | 97 | type: [String, Number],
|
98 | 98 | default: 'auto',
|
99 | 99 | },
|
| 100 | +
|
| 101 | + /** |
| 102 | + * it true, the dialog will add hash to the url. |
| 103 | + * and will be closed on browser back button. |
| 104 | + */ |
| 105 | + closeOnBack: { |
| 106 | + type: Boolean, |
| 107 | + default: false, |
| 108 | + }, |
100 | 109 | },
|
101 | 110 |
|
102 | 111 | emits: {
|
@@ -194,6 +203,47 @@ export default defineComponent({
|
194 | 203 | animateClick()
|
195 | 204 | }
|
196 | 205 |
|
| 206 | + // close on back button |
| 207 | + if (IN_BROWSER && props.closeOnBack) { |
| 208 | + const instace = getCurrentInstance()! |
| 209 | +
|
| 210 | + let currentDialogHash = `dialog-${instace.uid}` |
| 211 | + if (window.location.hash) |
| 212 | + currentDialogHash = `${window.location.hash.slice(1)}-${currentDialogHash}` |
| 213 | +
|
| 214 | + const popstateListener = () => { |
| 215 | + if (window.location.hash.includes(currentDialogHash) || !scopedModelValue.value) |
| 216 | + return |
| 217 | +
|
| 218 | + onClose() |
| 219 | + } |
| 220 | +
|
| 221 | + onMounted(() => { |
| 222 | + if (scopedModelValue.value) |
| 223 | + window.location.hash = currentDialogHash |
| 224 | +
|
| 225 | + window.addEventListener('popstate', popstateListener) |
| 226 | + }) |
| 227 | +
|
| 228 | + onUnmounted(() => { |
| 229 | + window.removeEventListener('popstate', popstateListener) |
| 230 | + }) |
| 231 | +
|
| 232 | + watch(scopedModelValue, (value) => { |
| 233 | + if (!value && window.location.hash.includes(currentDialogHash)) { |
| 234 | + window.history.back() |
| 235 | + } |
| 236 | + else if (value) { |
| 237 | + if (window.location.hash) |
| 238 | + currentDialogHash = `${window.location.hash.slice(1)}-${`dialog-${instace.uid}`}` |
| 239 | + else |
| 240 | + currentDialogHash = `dialog-${instace.uid}` |
| 241 | +
|
| 242 | + window.location.hash = `#${currentDialogHash}` |
| 243 | + } |
| 244 | + }) |
| 245 | + } |
| 246 | +
|
197 | 247 | // activator slot
|
198 | 248 | const activatorAttrs = {
|
199 | 249 | onClick() {
|
|
0 commit comments