Skip to content

fix(safeId): trigger id creation/update after mount (fixes #1978) #2161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Nov 12, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
}
}