@@ -12,16 +12,33 @@ import { getValue } from './path'
1212export default function ( Vue ) {
1313 const { isArray, isObject } = Vue . util
1414
15- function getVal ( key , lang , args ) {
16- let value = key
17- try {
18- let locale = Vue . locale ( lang )
19- let val = getValue ( locale , key ) || locale [ key ]
20- value = ( args ? format ( val , args ) : val ) || key
21- } catch ( e ) {
22- value = key
15+ function parseArgs ( ...args ) {
16+ let lang = Vue . config . lang
17+ if ( args . length === 1 ) {
18+ if ( isObject ( args [ 0 ] ) || isArray ( args [ 0 ] ) ) {
19+ args = args [ 0 ]
20+ } else if ( typeof args [ 0 ] === 'string' ) {
21+ lang = args [ 0 ]
22+ }
23+ } else if ( args . length === 2 ) {
24+ if ( typeof args [ 0 ] === 'string' ) {
25+ lang = args [ 0 ]
26+ }
27+ if ( isObject ( args [ 1 ] ) || isArray ( args [ 1 ] ) ) {
28+ args = args [ 1 ]
29+ }
2330 }
24- return value
31+
32+ return { lang, params : args }
33+ }
34+
35+ function translate ( locale , key , args ) {
36+ if ( ! locale ) { return null }
37+
38+ let val = getValue ( locale , key ) || locale [ key ]
39+ if ( ! val ) { return null }
40+
41+ return args ? format ( val , args ) : val
2542 }
2643
2744
@@ -36,23 +53,8 @@ export default function (Vue) {
3653 Vue . t = ( key , ...args ) => {
3754 if ( ! key ) { return '' }
3855
39- let language = Vue . config . lang
40- if ( args . length === 1 ) {
41- if ( isObject ( args [ 0 ] ) || isArray ( args [ 0 ] ) ) {
42- args = args [ 0 ]
43- } else if ( typeof args [ 0 ] === 'string' ) {
44- language = args [ 0 ]
45- }
46- } else if ( args . length === 2 ) {
47- if ( typeof args [ 0 ] === 'string' ) {
48- language = args [ 0 ]
49- }
50- if ( isObject ( args [ 1 ] ) || isArray ( args [ 1 ] ) ) {
51- args = args [ 1 ]
52- }
53- }
54-
55- return getVal ( key , language , args )
56+ const { lang, params } = parseArgs ( ...args )
57+ return translate ( Vue . locale ( lang ) , key , params ) || key
5658 }
5759
5860
@@ -64,8 +66,13 @@ export default function (Vue) {
6466 * @return {String }
6567 */
6668
67- Vue . prototype . $t = ( key , ...args ) => {
68- return Vue . t ( key , ...args )
69+ Vue . prototype . $t = function ( key , ...args ) {
70+ if ( ! key ) { return '' }
71+
72+ const { lang, params } = parseArgs ( ...args )
73+ return translate ( this . $options . locales && this . $options . locales [ lang ] , key , params )
74+ || translate ( Vue . locale ( lang ) , key , params )
75+ || key
6976 }
7077
7178 return Vue
0 commit comments