我将父子组件与 vueJs 一起使用。我目前必须为多个组件单独定义一种方法。
但是,我只想在一个地方定义它并在多个位置使用。
我的父模板是,
<campaign_segment :a=add(1,2)> </campaign_segment>
父模板的来源,
<template v-if="showTemplate" id="segment_body"> </template>
在 VueJS 中,
Vue.component(
'campaign_segment', {
template: '#segment_body',
props: ['a'],
methods:{
add: function(a,b){
return parseInt(a) + parseInt(b);
}
}
});
在这里,我应该为我的主 vuejs 对象定义方法“add()”。
否则我会收到错误消息“未定义添加方法”。
对于单个声明和组件触发有什么解决方案吗?
这怎么可能或有其他解决方案吗?
最佳答案
您正在寻找的功能名为 mixins在 vue JS 中。
Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.
所以你可以在mixin中添加一个方法,它将在所有mixin将被混合的组件中可用。请参阅以下示例:
// define a mixin object
var myMixin = {
methods: {
add: function(a,b){
return parseInt(a) + parseInt(b);
}
}
}
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [myMixin]
})
// alternate way to have a mixin while initialising
new Vue({
mixins: [myMixin],
created: function () {
console.log('other code')
}
})
关于javascript - 如何重用方法: define in main object and call from all component in VueJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157058/