Vuex - 跨模块共享通用功能

时间:2018-03-15 04:00:37

标签: javascript vuejs2 vuex

我正在开发一个Vue Js 2应用程序,我正在构建商店和不同的模块来分离代码。 有没有办法编写一个通用函数并在所有模块中共享它?

例如,我有一个函数truncate(),我需要在customer.js,cart.js,address.js中使用它。 如果我在store.js中声明它并尝试在模块中使用它会引发错误。 是出口和进口的唯一途径吗? 分享这个功能的最佳方式是什么?

3 个答案:

答案 0 :(得分:4)

对于 Vuex模块中的常见可重用功能,您可以使用Vuex Plugins

查看下面的示例。注意根店的使用情况:plugins: [myTruncatePlugin]



const myTruncatePlugin = store => {
  store.truncate = function(str) {
    return str.replace(/-/g, '') + ' ...was truncaaaated!'; // example implementation
  }
  // Note: I know this re-defines truncate() every time. This is just an example.
  // If it is such a problem, you could create it outside and just assign it here.
}

const moduleA = {
  namespaced: true,
  state: {name: "name@moduleA"},
  mutations: { changeName(state, data) { state.name = this.truncate(data); } },
}
const moduleB = {
  namespaced: true,
  state: {title: "title@moduleB"},
  mutations: { changeTitle(state, data) { state.title = this.truncate(data); } },
}
const myStore = new Vuex.Store({
  strict: true,
  modules: {
    aaa: moduleA,
    bbb: moduleB
  },
  plugins: [myTruncatePlugin]  // IMPORTANT: USAGE
});
new Vue({
  store: myStore,
  el: '#app',
  mounted: function() {
    setTimeout(() => {
      this.changeName("-n-e-w-N-A-M-E-");
      this.changeTitle("-n-e-w-T-I-T-L-E-");
    }, 200);
  },
  computed: {
    ...Vuex.mapState('aaa', ['name']),
    ...Vuex.mapState('bbb', ['title'])
  },
  methods: {
    ...Vuex.mapMutations('aaa', ['changeName']),
    ...Vuex.mapMutations('bbb', ['changeTitle'])
  }
})

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>

<div id="app">
  <p>moduleA's name: {{ name }}</p>
  <p>moduleB's title: {{ title }}</p>
</div>
&#13;
&#13;
&#13;

对于Vue实例中的常见可重用功能,您可以使用Mixins。对于最常见的情况,Global Mixin(谨慎使用):

&#13;
&#13;
Vue.mixin({
  methods: {
    truncate(str) {
      return str.replace(/-/g, '') + ' ...was truncaaaated!'; // example implementation
    }
  }
})

// this.truncate() will be available in all Vue instances...
new Vue({
  el: '#app1',
  data: {myStr1: '-o-n-e-'},
  mounted() { this.myStr1 = this.truncate(this.myStr1); }
})
new Vue({
  el: '#app2',
  data: {myStr2: '-t-w-o-'},
  mounted() { this.myStr2 = this.truncate(this.myStr2); }
})
// ...and components
Vue.component('my-comp', {
template: '#t3',
  data() { return {myStr3: '-t-h-r-e-e-'} },
  mounted() { this.myStr3 = this.truncate(this.myStr3); }
});
new Vue({
  el: '#app3',
})
&#13;
<script src="https://unpkg.com/vue@2.5.16/dist/vue.min.js"></script>

<div id="app1">App1: "{{ myStr1 }}"</div>
<div id="app2">App2: "{{ myStr2 }}"</div>

<template id="t3">
  <div>App3's component: "{{ myStr3 }}"</div>
</template>
<div id="app3"><my-comp></my-comp></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

@acdcjunior使用Mixins有最好的答案,但我只是在你的Vue实例中声明方法给你另一个选择。

以下示例,我在Vue实例中创建doTruncate方法,然后组件通过this.$parent.doTruncate

调用它们

// register
Vue.component('cart-component', {
  template: '<button @click="doTruncate">Cart Truncate!</button>',
  methods: {
  	doTruncate: function() {
    	this.$parent.doTruncate("Hello from cart");
    }
  }
})

// register
Vue.component('customer-component', {
  template: '<button @click="doTruncate">Customer Truncate!</button>',
  methods: {
  	doTruncate: function() {
    	this.$parent.doTruncate("Hello from customer");
    }
  }
})

var app3 = new Vue({
  el: '#app',
  methods: {
  	doTruncate: function(params) {
    	alert(params);
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.15/dist/vue.js"></script>
<div id="app">
<cart-component></cart-component>
<br>
<customer-component></customer-component>
<br>
<button @click="doTruncate('Hello from parent')">
Parent!
</button>
</div>

答案 2 :(得分:0)

你可以使用vue js事件来共享像

这样的功能

eventBus.js //它将创建公共实例

import Vue from 'vue';
export const eventBus = new Vue();

common.js //您的常用功能将进入此文件

import { eventBus } from '<path of file>'; 

mounted() {
    eventBus.$on('truncate',()=> {
        this.truncate();
    })
}

methods: {
    truncate(){
        //truncate code
    }
}

customer.js //从customer.js

调用您的常见截断函数
import { eventBus } from '<path of file>'; 
eventBus.$emit('truncate');
相关问题