[英]Vue.js - Composition API - Toggle Button
I am working on a Vue.js app.我正在开发一个 Vue.js 应用程序。 I am determined to understand the Composition API.
我决心了解 Composition API。 However, the syntax throws me off a bit.
然而,语法让我有点失望。 I feel like I'm creating closures inside of closures, which leads me to believe I'm doing it wrong.
我觉得我在闭包内创建闭包,这让我相信我做错了。 I'm trying to set whether a button is enabled/disabled when my component loads.
我正在尝试设置在我的组件加载时是否启用/禁用按钮。 To demonstrate, I've created this fiddle , which includes the following:
为了演示,我创建了这个fiddle ,其中包括以下内容:
example例子
myApp.component("banner",
{
template: '<button :disabled="isDisabled">generate</button>',
setup(props) {
let isDisabled = true;
function initializeButton() {
fetch('<some-url>')
.then(res => { isDisabled = !res.ok; } )
;
}
initializeButton();
return {
isDisabled
};
}
}
);
However, this does not work.但是,这不起作用。 I've narrowed it down to the fact that
isDisabled
is not "accessible" in the then
part of the promise.我已将范围缩小到在承诺的
then
部分中isDisabled
不可“访问”这一事实。 However, I'm unsure how to actually set isDisabled
in then
.但是,我不确定如何在
then
实际设置isDisabled
。 Plus, I would love to put the initializeButton
outside of the setup
method, even that, I couldn't do though.另外,我很想把
initializeButton
的外面setup
方法,即使如此,我不能这样做,虽然。 I appreciate anyone's help who can help me out.我感谢任何可以帮助我的人的帮助。
Thank you.谢谢你。
To have an asynchronous setup method you need to use suspense
.要使用异步设置方法,您需要使用
suspense
。
@vue-composition / How can I use asynchronous methods in setup() @vue-composition / 如何在 setup() 中使用异步方法
Example :例子 :
Vue.productionTip = false; const Todo = { async setup(props) { const todo = await fetch('https://jsonplaceholder.typicode.com/todos/1') .then(r => r.json()); return { todo } }, template: ` <div> Todo : {{ todo.title }} </div> ` }; const vm = Vue.createApp({ components: { Todo } }).mount('#app')
<script src="https://unpkg.com/vue@next"></script> <div id="app"> <Suspense> <template #default> <Todo /> </template> <template #fallback> <div>Loading...</div> </template> </Suspense> </div>
Also isDisabled
is not reactive. isDisabled
是反应性的。 You need to use ref
to make this varible reactive.您需要使用
ref
使该变量具有反应性。
basic example for reactivity with ref:与 ref 反应的基本示例:
Vue.productionTip = false; const vm = Vue.createApp({ setup(props) { const count = Vue.ref(0); const inc = () => { count.value += 1; } return { count, inc } } }).mount('#app')
<script src="https://unpkg.com/vue@next"></script> <div id="app"> Count : {{ count }} <button @click="inc">+1</button> </div>
Since initializeButton
is an asynchronous operation you should use the await
syntax ( https://javascript.info/async-await )由于
initializeButton
是一个异步操作,你应该使用await
语法( https://javascript.info/async-await )
async setup() {
function async initializeButton() {
return fetch('<some-url>').then(res => { isDisabled = !res.ok; } );
}
await initializeButton();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.