diff --git a/src/extend.js b/src/extend.js index 8bba945ae..b86bdfbe2 100644 --- a/src/extend.js +++ b/src/extend.js @@ -1,26 +1,47 @@ /* @flow */ export default function extend (Vue: any): void { - Vue.prototype.$t = function (key: Path, ...values: any): TranslateResult { - const i18n = this.$i18n - return i18n._t(key, i18n.locale, i18n._getMessages(), this, ...values) - } - - Vue.prototype.$tc = function (key: Path, choice?: number, ...values: any): TranslateResult { - const i18n = this.$i18n - return i18n._tc(key, i18n.locale, i18n._getMessages(), this, choice, ...values) - } - - Vue.prototype.$te = function (key: Path, locale?: Locale): boolean { - const i18n = this.$i18n - return i18n._te(key, i18n.locale, i18n._getMessages(), locale) - } - - Vue.prototype.$d = function (value: number | Date, ...args: any): DateTimeFormatResult { - return this.$i18n.d(value, ...args) - } - - Vue.prototype.$n = function (value: number, ...args: any): NumberFormatResult { - return this.$i18n.n(value, ...args) - } + // $FlowFixMe + Object.defineProperty(Vue.prototype, '$t', { + get () { + return (key: Path, ...values: any): TranslateResult => { + const i18n = this.$i18n + return i18n._t(key, i18n.locale, i18n._getMessages(), this, ...values) + } + } + }) + // $FlowFixMe + Object.defineProperty(Vue.prototype, '$tc', { + get () { + return (key: Path, choice?: number, ...values: any): TranslateResult => { + const i18n = this.$i18n + return i18n._tc(key, i18n.locale, i18n._getMessages(), this, choice, ...values) + } + } + }) + // $FlowFixMe + Object.defineProperty(Vue.prototype, '$te', { + get () { + return (key: Path, locale?: Locale): boolean => { + const i18n = this.$i18n + return i18n._te(key, i18n.locale, i18n._getMessages(), locale) + } + } + }) + // $FlowFixMe + Object.defineProperty(Vue.prototype, '$d', { + get () { + return (value: number | Date, ...args: any): DateTimeFormatResult => { + return this.$i18n.d(value, ...args) + } + } + }) + // $FlowFixMe + Object.defineProperty(Vue.prototype, '$n', { + get () { + return (value: number, ...args: any): NumberFormatResult => { + return this.$i18n.n(value, ...args) + } + } + }) } diff --git a/test/unit/issues.test.js b/test/unit/issues.test.js index d4bcb0937..0b0791ac6 100644 --- a/test/unit/issues.test.js +++ b/test/unit/issues.test.js @@ -285,4 +285,33 @@ describe('issues', () => { }).then(done) }) }) + + describe('#259', () => { + it('this points to the right', (done) => { + const vm = new Vue({ + i18n: new VueI18n({ + locale: 'en', + messages: { + en: { + 'hello': 'hello #259' + }, + ja: { + 'hello': 'こんにちは #259' + } + } + }) + }) + const $t = vm.$t + const $tc = vm.$t + const $te = vm.$t + const $d = vm.$t + const $n = vm.$t + assert.equal($t('hello'), 'hello #259') + assert.equal($tc('hello'), 'hello #259') + assert.equal($te('hello'), 'hello #259') + assert.equal($d('hello'), 'hello #259') + assert.equal($n('hello'), 'hello #259') + done() + }) + }) })