Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

10 实现简单的插件 - i18n #12

Open
xwjie opened this issue Jan 13, 2018 · 0 comments
Open

10 实现简单的插件 - i18n #12

xwjie opened this issue Jan 13, 2018 · 0 comments

Comments

@xwjie
Copy link
Owner

xwjie commented Jan 13, 2018

在之前的基础上,简单的实现一个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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant