javascript - 如何重用方法: define in main object and call from all component in VueJS

标签 javascript vue-component vue.js vuejs2

我将父子组件与 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/

相关文章:

typescript - 使用模板字符串预编译 TypeScript Vue 组件

javascript - 异步函数 - 数据函数应该返回一个对象?

javascript - Vue.js CLI 3 - 如何为 CSS/Sass 创建 vendor 包?

javascript - 指令不工作 AngularJS

javascript - 如何迭代 JSON 数据并添加单独的 CSS?

javascript - 从文件读入配置

javascript - jQuery 自定义快门

javascript - Vue-Select 事件触发器,无需 Node.js

javascript - 我应该将所有组件注册到 app.js 还是导入 vue 组件

javascript - 从 Vue 组件内的 URL 导入 PayPal(或任何其他脚本)