chore: initial import
This commit is contained in:
91
store/$t.mixin.js
Normal file
91
store/$t.mixin.js
Normal file
@@ -0,0 +1,91 @@
|
||||
import { mapState } from 'vuex'
|
||||
import store from '@/store'
|
||||
import {
|
||||
getCurrentLocale,
|
||||
getLocaleShort,
|
||||
getNextLocale,
|
||||
normalizeLocale,
|
||||
pickLocalizedText,
|
||||
translateGlobalMessages,
|
||||
translateMessages
|
||||
} from '@/utils/i18n'
|
||||
import { syncNavigationBarTitle } from '@/utils/navigation-title'
|
||||
|
||||
// 尝试将用户在根目录中的store/index.js的vuex的state变量加载到全局变量中
|
||||
let $tStoreKey = []
|
||||
try {
|
||||
$tStoreKey = store.state ? Object.keys(store.state) : []
|
||||
} catch(e) {
|
||||
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
beforeCreate() {
|
||||
this.$t.vuex = (name, value) => {
|
||||
this.$store.commit('$tStore', {
|
||||
name, value
|
||||
})
|
||||
}
|
||||
},
|
||||
onShow() {
|
||||
this.$syncNavigationTitle()
|
||||
},
|
||||
watch: {
|
||||
vuex_locale() {
|
||||
this.$nextTick(() => {
|
||||
this.$syncNavigationTitle()
|
||||
if (typeof this.$forceUpdate === 'function') {
|
||||
this.$forceUpdate()
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
// 将vuex的state中的变量结构到全局混入mixin中
|
||||
...mapState($tStoreKey)
|
||||
},
|
||||
methods: {
|
||||
$getLocale() {
|
||||
return normalizeLocale(this.vuex_locale || getCurrentLocale())
|
||||
},
|
||||
$getLanguage() {
|
||||
return getLocaleShort(this.$getLocale())
|
||||
},
|
||||
$setLocale(locale) {
|
||||
const nextLocale = normalizeLocale(locale)
|
||||
this.$store.commit('$tStore', {
|
||||
name: 'vuex_locale',
|
||||
value: nextLocale
|
||||
})
|
||||
return nextLocale
|
||||
},
|
||||
$toggleLocale() {
|
||||
return this.$setLocale(getNextLocale(this.$getLocale()))
|
||||
},
|
||||
$translate(messages, key, params) {
|
||||
return translateMessages(messages, this.$getLocale(), key, params)
|
||||
},
|
||||
$tm(namespace, key, params) {
|
||||
return translateGlobalMessages(namespace, this.$getLocale(), key, params)
|
||||
},
|
||||
$pickText(zh, en, fallback = '') {
|
||||
return pickLocalizedText({
|
||||
zh,
|
||||
en,
|
||||
fallback,
|
||||
locale: this.$getLocale()
|
||||
})
|
||||
},
|
||||
$getCurrentPageRoute() {
|
||||
const pages = getCurrentPages()
|
||||
if (!Array.isArray(pages) || !pages.length) {
|
||||
return ''
|
||||
}
|
||||
const currentPage = pages[pages.length - 1] || {}
|
||||
return currentPage.route || ''
|
||||
},
|
||||
$syncNavigationTitle(route) {
|
||||
return syncNavigationBarTitle(route || this.$getCurrentPageRoute(), this.$getLocale())
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user