1

I'm new to Vue.js and looking for the equivalent of a service in AngularJS, specifically for storing data once and getting it throughout the app.

I'll be mainly storing the results of network requests and other promised data so I don't need to fetch again on very state.

I'm using Vue.JS 2.0 with Webpack.

Thanks!

2 Answers 2

2

I think what u are seeking for is vuex, which can share data from each component.

Here is a basic demo which from my code.

store/lottery.module.js

import lotteryType from './lottery.type'


const lotteryModule = {

    state: {participantList: []},
    getters: {},
    mutations: {
        [lotteryType.PARTICIPANT_CREATE] (state, payload) {
            state.participantList = payload;
        }
    },
    actions: {
        [lotteryType.PARTICIPANT_CREATE] ({commit}, payload) {

            commit(lotteryType.PARTICIPANT_CREATE, payload);
        }
    }
};

export default lotteryModule;

store/lottery.type.js

const PARTICIPANT_CREATE = 'PARTICIPANT_CREATE';

export default {PARTICIPANT_CREATE};

store/index.js

Vue.use(Vuex);
const store = new Vuex.Store();
store.registerModule('lottery', lotteryModule);

export default store;

component/lottery.vue

<template>

<div id="preparation-container">
    Total Participants: {{participantList.length}}
</div>

</template>


<script>

import router from '../router';
import lotteryType from '../store/lottery.type';


export default {
    data () {
        return {
        }
    },
    methods: {
    },
    computed: {
        participantList() {
            return this.$store.state.lottery.participantList;
        }
    },
    created() {
        this.$store.dispatch(lotteryType.PARTICIPANT_CREATE, [{name:'Jack'}, {name:'Hugh'}]);
    },
    mounted() {

    },
    destroyed() {

    }
}

</script>
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need Vue-specific services in Vue2 as it is based on a modern version of JavaScript that uses Modules instead. So if you want to reuse some services in different locations in your code, you could define and export it as follows:

export default {
    someFunction() {
        // ...
    },
    someOtherFunction() {
        // ...
    }
};

And then import from your Vue code:

import service from 'filenameofyourresources';

export default {
    name: 'something',
    component: [],
    data: () => ({}),
    created() {
        service.someFunction();
    },
};

Note that this is ES6 code that needs to be transpiled to ES5 before you can actually use it todays browsers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.