Mixing Nextcloud Globals into Vue
Nextcloud apps use global functions to access server APIs like the t
function to translate
a given string. Within a Vue template, you can use this function like this:
<template>
<span>{{ t('myapp', 'Hello, {user}', {user: this.user})}}</span>
</template>
<script>
export default {
props: ['user']
}
</script>
However, this won’t work. You will see a TypeError: _vm.t is not a function
error in your
browser’s console:
So far the easiest and cleanest way to fix this I have found is writing a tiny Vue mixin:
// src/mixins/Nextcloud.js
export default {
methods: {
t
}
}
This mixin makes the global function t
available as instance method. It can be
used in an app globally via the entry script:
// src/main.js
import Vue from 'vue'
import Nextcloud from './mixins/Nextcloud'
Vue.mixin(Nextcloud)
Alternatively, it can also be applied to specific components only:
// src/components/MyComponent.js
<tempate>
...
</template>
<script>
import Nextcloud from '../mixins/Nextcloud'
export default {
props: ['user'],
mixins: [Nextcloud]
}
</script>
Testing
This trick is also handy for testing scenarios where the globals aren’t available. There a slightly adjusted mixin can provide stubs for Nextcloud’s global functions:
// src/tests/mixins/Nextcloud.js
export default {
methods: {
t: (app, str) => str
}
}
Update 2018-10-23: fixed typo.