gpt4 book ai didi

javascript - 使用当前 vue 组件的方法作为默认的 prop 值

转载 作者:搜寻专家 更新时间:2023-10-30 22:22:23 24 4
gpt4 key购买 nike

我将把函数作为属性传递给 Vue 组件。让它成为必须由 @click 调用的函数。但出于某些原因,我想保留组件的默认行为。默认行为并不像我想要的那么容易,我将使用 method 作为默认函数。因为默认行为需要来自组件状态的数据( Prop 、数据、其他方法等)。

有办法吗?

我附上了例子。预期行为:

按钮工作正常应该产生警报不客气!
按钮 nope 应该产生警报 也欢迎您! 但什么都不做。

Vue.component('welcome-component', {
template: '#welcome-component',
props: {
name: {
type: String,
required: true,
},
action: {
type: Function,
required: false,
default: () => { this.innerMethod() },
},
},
methods: {
innerMethod() {
alert("You are welcome as well!");
}
}
});


var app = new Vue({
el: "#app",
methods: {
externalMethod() {
alert("You are welcome!");
}
}
});
#app {
margin: 20px;
}

.holder > button {
margin: 10px;
padding: 5px;
font-size: 1.1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<welcome-component name="works fine" :action="externalMethod"></welcome-component>
<welcome-component name="nope"></welcome-component>
</div>


<script id='welcome-component' type='x-template'>
<div class="holder">
<button @click="action">{{ name }}</button>
</div>
</script>

最佳答案

这行得通,但它是一整套 Spanner :

action: {
required: false,
default () {
return () => this.innerMethod();
},
},

我不得不删除 type: Function。通常当 default 是一个函数时,它将被调用以返回适当的默认值。但是,如果 prop 具有 type: Function,它只会将函数视为默认值。在这种情况下,这是有问题的,因为我们丢失了 this 绑定(bind)。

需要内部箭头函数来解决调用 default 函数时方法不可用的问题。

如果可能的话,我会建议放弃使用 default,而只是在需要调用时应用“default”。因此,不是直接在 click 处理程序中调用 action,而是调用一个名为 invokeAction 的方法,它看起来像这样:

invokeAction () {
if (this.action) {
this.action();
} else {
this.innerMethod();
}
}

关于javascript - 使用当前 vue 组件的方法作为默认的 prop 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57313153/

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