I'm working on a component that takes care of registering my users to Sinch (voip platform). In order for my registration to work I need to have some variables that are accessible throughout my component methods. I'm wondering how this should be done using vue.
I need my variable sinchClient
to be accessible in my methods newUserRequest()
and loginRequest()
Any tips?
Sinch variable
var sinchClient = new SinchClient({
applicationKey: "My-Key",
capabilities: {
messaging: true,
calling: true
},
supportActiveConnection: true,
onLogMessage: function(msg) {
console.log(msg);
}
});
Methods
<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>
You can define sinchClient
globally and access it using window (window.sinchClient
). Better you can create a Vue plugin and inject it in the app context:
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 }
})
}
})
And access it with this.$sinchClient
in Vue context