-
Notifications
You must be signed in to change notification settings - Fork 11
Open
Description
在之前的基础上,简单的实现一个i18n的小插件,一共只有10几行代码。
测试代码
<!DOCTYPE html>
<html>
<head>
<title>Xiao框架之helloworld</title>
<script src="../dist/xiao.js"></script>
</head>
<body>
<h1>简单的国际化插件i18n测试</h1>
<div id="demo1">
<h1>1层的信息:{{ $t("msg1") }}</h1>
<h1>2层的信息:{{ $t("message.hello") }}</h1>
</div>
<a href="#" onclick="i18n.locale='en';app.$forceUpdate()">英语</a>
<a href="#" onclick="i18n.locale='cn';app.$forceUpdate()">中文</a>
<script>
var messages = {
en: {
msg1: 'message 1',
message: {
hello: 'hello world'
}
},
cn: {
msg1:'信息1',
message: {
hello: '你好世界'
}
}
}
var i18n = {
locale: 'cn', // set locale
messages, // set locale messages
}
var app = new Xiao( {
i18n: i18n
});
app.$mount("#demo1");
</script>
</body>
</html>
增加强制刷新方法
强制重新渲染一次,把render对应的watch update一下即可。
class Xiao{
/**
* 强制刷新
*/
$forceUpdate(){
this._renderWatcher.update()
}
}
实现i18n插件代码
/**
* 简单的i18n国际化插件
* @param {*} Xiao
*/
export default function (Xiao: Xiao) {
// 扩展一个实例方法
Xiao.prototype.$t = function (key) {
const instance = this.$options.i18n
console.log('i18n', instance)
if (instance) {
const keys = key.split('.')
let msg = instance.messages[instance.locale]
for (let i = 0; i < keys.length; i++) {
msg = msg[keys[i]]
}
return msg
}
else {
return key
}
}
console.log('i18n组件注册完毕')
}
注册插件
import i18n from './plugins/i18n'
// 注册默认插件
Xiao.use(i18n)
Metadata
Metadata
Assignees
Labels
No labels