Mixing Nextcloud Globals into Vue
source link: https://blog.wuc.me/2018/10/22/mixing-nextcloud-globals-into-vue.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Mixing Nextcloud Globals into Vue
1 minute read
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>
TestingPermalink
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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK