我正在处理两个组件之间的通信(使用Vue 2),其中一个是按钮,可以具有初始、加载和完成(成功或失败)等状态,对于按钮的每个状态,我可能会显示不同的文本,不同的图标(加载:旋转图标,成功完成:勾号,错误完成:x),我还有一个表单,将使用按钮组件。我不确定如何根据表单提交的当前状态来更改按钮的状态。请查看下面的代码。
我的按钮组件:
<template>
<button
class="ui-button"
@click="clicked"
:data-status-type="status_type"
:disabled="is_disabled"
:type="type"
>
<i :class="icon" v-if="is_disabled || concluded"></i>
{{ title }}
</button>
</template>
<script>
export default {
props: {
title: {
type: String,
},
type: {
default: "button",
type: String,
},
},
data() {
return {
concluded: false,
icon: "fa fa-spin ",
is_disabled: false,
status_type: "success",
};
},
methods: {
clicked() {
if (!this.is_disabled) {
this.$emit(
"clicked",
() => {
this.is_disabled = true;
this.icon = "fa fa-spin fas fa-spinner";
},
(succeeded) => {
this.is_disabled = false;
this.concluded = true;
this.icon = succeeded ? "fas fa-check" : "fas fa-xmark";
this.status_type = succeeded ? "success" : "error";
setTimeout(() => {
this.concluded = false;
this.icon = "";
this.status_type = "";
}, 1500);
}
);
}
},
},
};
</script>
我的表单组件:
<template>
<div>
<ThePages :parents="accompaniments">
<!-- ... some reactive stuff -->
<template #extra_button>
<TheButton @clicked="sendItemToCart" :title="button_text" :disabled="button_disabled" />
</template>
</ThePages>
</div>
</template>
<script>
import axios from 'axios'
import FormatHelper from '../helpers/FormatHelper'
import SwalHelper from '../helpers/SwalHelper'
import TheButton from './TheButton.vue'
import ThePages from './ThePages.vue'
import TheQuantityPicker from './TheQuantityPicker.vue'
export default {
props: ['product'],
components: {
TheButton,
ThePages,
TheQuantityPicker,
},
data() {
return {
accompaniments: this.product.accompaniment_categories,
button_text: '',
button_disabled: false,
format_helper: FormatHelper.toBRCurrency,
observation: '',
quantity: 1,
success: false,
}
},
created() {
this.addQuantityPropToAccompaniments()
this.availability()
},
methods: {
// ... some other methods
async sendItemToCart(startLoading, concludedSuccessfully) {
startLoading() // This will change the button state
this.button_text = 'Adicionando...'
await axios
.post(route('cart.add'), {
accompaniments: this.buildAccompanimentsArray(),
id: this.product.id,
quantity: this.quantity,
observation: this.observation,
})
.then(() => {
concludedSuccessfully(true) // This will change the button state
this.button_text = 'Adicionado'
SwalHelper.productAddedSuccessfully()
})
.catch((error) => {
concludedSuccessfully(false) // This will change the button state
if (
error?.response?.data?.message ==
'Este produto atingiu a quantidade máxima para este pedido.'
) {
SwalHelper.genericError(error?.response?.data?.message)
} else {
SwalHelper.genericError()
}
this.button_text = 'Adicionar ao carrinho'
})
},
},
}
</script>
在上面的代码中,您可以看到我如何根据表单的状态来更改按钮的状态:我的按钮在点击时发出两个函数(startLoading,concludedSuccessfully),然后我在sendItemToCart中使用这两个函数。
这似乎将两个组件耦合得有点太多了,因为我必须将这些函数作为参数传递给父组件的方法。另外,我对如何做到这一点还有另一个想法,那就是给每个按钮一个ref,然后在父组件中使用ref调用其方法。这个想法听起来有点像面向对象编程中的“组合而非继承”,我只需要求对象/组件做某事,但在这种情况下,没有将函数作为参数。
嗯,上面的两种情况似乎比我可能拥有的每个按钮都创建变量更好,但它们似乎可以改进。所以我正在寻找的是:如何更好地解耦我的组件?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果我们讨论的是Vue 3(你没有指定Vue的版本,所以不确定是Vue 2),你可能正在寻找
provide/inject:https://vuejs.org/guide/components/provide-inject.html
所以,如果你有一个父组件和一堆子组件,这些子组件只能作为父组件的后代出现(例如表单和输入框),你可以
provide表单的状态:OP评论说按钮也可能出现在其他地方,所以我们应该同时使用props和provide。在没有表单的情况下,我们可以使用props作为默认的注入值。
在表单组件中:
<script setup> import {reactive, provide} from 'vue'; const form = reactive({button_disabled: false, button_text: '', sendItemToCart}); provide('form', form); function sendItemToCart(){ // your logic here } </script> <template> <div> <ThePages :parents="accompaniments"> <!-- ... some reactive stuff --> <template #extra_button> <TheButton /> </template> </ThePages> </div> </template>在按钮组件中:
<script setup> import {inject} from 'vue'; const props = defineProps('button_disabled button_text'.split(' ')); const form = inject('form', props); // use either provide of props </setup> <template> <button class="ui-button" @click="() => form.sendItemToCart ? form.sendItemToCart() : $emit('clicked')" :data-status-type="status_type" :disabled="form.button_disabled" :type="type" > <i :class="icon" v-if="form.button_disabled || concluded"></i> {{ form.button_text }} </button> </template>将代码调整为Options API。
使用Vue 2进行更新
OP更正了答案,使用的是Vue 2。所以...
幸运的是,Vue 2也支持
provide/inject!唯一的问题是如何使provide具有响应性,我猜在这里得到了解决:How do I make Vue 2 Provide / Inject API reactive?