【发布时间】:2019-12-10 07:04:48
【问题描述】:
我要将函数作为属性传递给 Vue 组件。让它成为函数必须由@click 调用。但由于某些原因,我想保留组件的默认行为。默认行为并不像我想要的那么简单,我将使用method 作为默认函数。因为默认行为需要来自组件状态的数据(道具、数据、其他方法等)。
有办法吗?
我已附上示例。预期行为:
按钮works fine 应该产生警报You are welcome!
按钮 nope 应该产生警报 You are welcome as well! 但什么也不做。
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>
【问题讨论】:
-
default: () => {如何在不在范围内的箭头函数内引用this?还是它在 Vue 编译器的范围内神奇地存在?还是我错过了什么? -
@JamesHarrington 完全正确。这是问题。
-
啊@MartenCatcher 感谢您的澄清。 :)
标签: javascript vue.js vuejs2 vue-component