Mat*_*s S 5 vue.js vue-component vuejs2
我正在尝试使我的Vue组件可重用,但其中有一部分需要在按钮单击上运行一个函数,我在父组件中定义了该函数.组件的按钮将始终运行父函数,它传递的参数始终相同(唯一的其他属性).
现在我将2个属性传递给组件:1)一个对象和2)父函数引用,它需要来自1)的对象作为参数.
该儿童 -component看起来像这样(去除不必要的代码):
<button v-on:click="parentMethod(placement)">Analyze</button>
Vue.component('reporting-placement', {
props: ['placement', 'method'],
template: '#reporting-placement',
methods: {
parentMethod: function(placement) {
this.method(placement);
}
}
});
Run Code Online (Sandbox Code Playgroud)
该家长是利用这样子的:
<reporting-placement v-bind:placement="placement" v-bind:method="analyzePlacement"></reporting-placement>
methods: {
analyzePlacement: function(placement) {
this.active_placement = placement;
},
}
Run Code Online (Sandbox Code Playgroud)
如您所见,子项只有一个属性placement,以及回调引用.在placement必须放在作为参数从父参考作用.
但是由于父级定义了参数,因此子级不应该关注它需要传递给父函数的内容.相反,我宁愿已经在父对象中传递参数.
而不是
<reporting-placement v-bind:placement="placement" v-bind:method="analyzePlacement"></reporting-placement>
Run Code Online (Sandbox Code Playgroud)
我会比较喜欢
<reporting-placement v-bind:placement="placement" v-bind:method="analyzePlacement(placement)"></reporting-placement>
Run Code Online (Sandbox Code Playgroud)
(包括孩子的适当变化).但传递参数不会那样.是否有可能(可能在其他语法中)将变量"绑定"到函数引用,以便在调用回调时自动传递?
信息:如果我将其写下来,我没有收到错误信息,但是当我将参数传递给组件时,整个Vue都会搞砸.
希望问题很清楚:-)非常感谢!
通过阅读你的建议我发现你过度使用道具传递.
您对子组件不应该对父组件使用数据的方式有任何了解的担心是完全可以接受的.要实现这一点,您可以使用Vue的事件广播系统,而不是将方法作为道具传递.所以你的代码会变成这样:
Vue.component('reporting-placement', {
props: ['placement', 'method'],
template: '#reporting-placement',
methods: {
parentMethod: function(placement) {
this.$emit('reporting-placement-change', placement)
}
}
});
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
<reporting-placement v-bind:placement="placement" @reporting-placement-change="analyzePlacement($event)"></reporting-placement>
Run Code Online (Sandbox Code Playgroud)
但是如果您需要父方法提供的数据,最好考虑使用状态管理系统(可以是简单的EventBus或事件,更复杂的Vuex)
最后,如果你真的喜欢/必须将方法作为道具传递,你可以将它放在一个对象中,并将该对象作为道具传递.
| 归档时间: |
|
| 查看次数: |
5702 次 |
| 最近记录: |