如何在组件方法中具有可访问的变量

时间:2019-01-03 21:27:50

标签: javascript vue.js sinch

我正在开发一个组件,该组件负责将我的用户注册到Sinch(voip平台)。为了使我的注册有效,我需要一些在整个组件方法中都可以访问的变量。我想知道如何使用vue做到这一点。

我需要在方法sinchClientnewUserRequest()中访问变量loginRequest()

有什么提示吗?

插入变量

var sinchClient = new SinchClient({
  applicationKey: "My-Key",
  capabilities: {
    messaging: true,
    calling: true
  },
  supportActiveConnection: true,
  onLogMessage: function(msg) {
    console.log(msg);
  }
});

方法

<script>
export default {
  data() {
    return {
      username: null,
      name: null,
      password: null,
      loggedIn: false
    };
  },
  mounted() {},
  methods: {
    newUserRequest() {
      console.log(this.name, this.password);

      if (this.name && this.password) {
        var handleSuccess = () => {
          console.log("User created");
          this.loggedIn = true;
          this.name = sinchClient.user.userId;
        };
        var handleFail = error => {
          console.log(error.message);
        };

        var signUpObject = { username: this.name, password: this.password };
        sinchClient
          .newUser(signUpObject)
          .then(sinchClient.start.bind(sinchClient))
          .then(() => {
            localStorage[
              "sinchSession-" + sinchClient.applicationKey
            ] = JSON.stringify(sinchClient.getSession());
          })
          .then(handleSuccess)
          .fail(handleFail);
      }
    },
    logInRequest() {
      if (this.name && this.password) {
        var handleSuccess = () => {
          console.log("User logged in");
          this.loggedIn = true;
          this.name = sinchClient.user.userId;
        };
        var handleFail = error => {
          console.log(error.message);
        };
        var signUpObject = { username: this.name, password: this.password };
        sinchClient
          .start(signUpObject)
          .then(() => {
            localStorage[
              "sinchSession-" + sinchClient.applicationKey
            ] = JSON.stringify(sinchClient.getSession());
          })
          .then(handleSuccess)
          .fail(handleFail);
      }
    }
  }
};
</script>

1 个答案:

答案 0 :(得分:3)

您可以全局定义sinchClient并使用窗口(window.sinchClient)对其进行访问。更好的是,您可以创建一个Vue插件并将其注入应用程序上下文中:

var sinchClient = new SinchClient({
  applicationKey: "My-Key",
  capabilities: {
    messaging: true,
    calling: true
  },
  supportActiveConnection: true,
  onLogMessage: function(msg) {
    console.log(msg);
  }
})
Vue.use({
  install: function(Vue) {
    Object.defineProperty(Vue.prototype, '$sinchClient', {
      get () { return sinchClient }
    })
  }
})

并在Vue上下文中使用this.$sinchClient进行访问