gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:13:11 24 4
gpt4 key购买 nike

我正在开发一个组件,负责将我的用户注册到 Sinch(VoIP 平台)。为了让我的注册工作,我需要有一些可以通过我的组件方法访问的变量。我想知道如何使用 vue 来完成此操作。

我需要在我的方法 newUserRequest()loginRequest() 中访问我的变量 sinchClient

有什么建议吗?

正弦变量

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>

最佳答案

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

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 访问它

关于javascript - 如何在组件方法中具有可访问的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54030037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com