как иметь доступные переменные в компонентных методах - PullRequest
0 голосов
/ 04 января 2019

Я работаю над компонентом, который заботится о регистрации моих пользователей в Sinch (платформа VoIP).Для того, чтобы моя регистрация работала, мне нужно иметь некоторые переменные, которые доступны во всех моих компонентных методах.Мне интересно, как это сделать с помощью vue.

Мне нужна моя переменная sinchClient, чтобы она была доступна в моих методах newUserRequest() и loginRequest()

Любые советы?

Переменная Sinch

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 голосов
/ 04 января 2019

Вы можете определить 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 }
    })
  }
})

И получить к нему доступ с помощью this.$sinchClient в контексте Vue

...