Skip to content

Commit

Permalink
fix(safeId): trigger id creation/update after mount (fixes #1978) (#2161
Browse files Browse the repository at this point in the history
)

* fix(safeId): trigger id update on mount.

Uses computed prop to generate a method that returns the ID, which has the same call arguments as the original safeID(suffix) method
  • Loading branch information
tmorehouse authored Nov 12, 2018
1 parent 4bb17f3 commit 48218fe
Showing 1 changed file with 27 additions and 12 deletions.
39 changes: 27 additions & 12 deletions src/mixins/id.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/*
* SSR Safe Client Side ID attribute generation
*
* id's can only be generated client side, after mount.
* this._uid is not synched between server and client.
*/

export default {
Expand All @@ -10,21 +11,35 @@ export default {
default: null
}
},
methods: {
safeId (suffix = '') {
const id = this.id || this.localId_ || null
if (!id) {
return null
}
suffix = String(suffix).replace(/\s+/g, '_')
return suffix ? id + '_' + suffix : id
data () {
return {
localId_: null
}
},
mounted () {
// mounted only occurs client side
this.$nextTick(() => {
// Update dom with auto ID after dom loaded to prevent
// SSR hydration errors.
this.localId_ = `__BVID__${this._uid}`
})
},
computed: {
localId_ () {
if (!this.$isServer && !this.id && typeof this._uid !== 'undefined') {
return '__BVID__' + this._uid
safeId () {
// Computed property that returns a dynamic function for creating the ID.
// Reacts to changes in both .id and .localId_ And regens a new function
const id = this.id || this.localId_

// We return a function that accepts an optional suffix string
// So this computed prop looks and works like a method!!!
const fn = (suffix) => {
if (!id) {
return null
}
suffix = String(suffix || '').replace(/\s+/g, '_')
return suffix ? id + '_' + suffix : id
}
return fn
}
}
}

0 comments on commit 48218fe

Please sign in to comment.