DevonDahon
DevonDahon

Reputation: 8350

Laravel & Vuejs mixins : how to attribute a new value to shared variable?

I can use the mixin variables test and the method changeTest, when when I attribute a new value to the variable test, it's only applied in one component. How to have it changed globally, on all components using it ?

My mixins are set in the file resources/js/mixins.js:

export default {
    data() {
        return {
            test: 'foo',
        };
    },
    methods: {
        changeTest(v) {
            this.test = v;
        }
    }
}

Then, I have my two components comp1.vue and comp2.vue in resources/js/components/, both looking like this:

<template>
  <div>
    {{ test }}
  </div>
</template>

<script>
import myMixins from '../mixins'
export default {
  mixins: [ myMixins ],
}
</script>

Both components are in my home.blade.php like this:

@extends('layouts.app')

@section('content')

<comp1></comp1>
<comp2></comp2>

@ensection

Upvotes: 1

Views: 2850

Answers (2)

Mehdi
Mehdi

Reputation: 756

for making a common variable (state) between all instances in vue.js you can use vuex. it's so simple, just add vuex to your packages and make an instance like this:

import Vuex from 'vuex'

const store = new Vuex.Store({
    state: {
        test: 'foo',
    },
    mutations: {
        setTest(state, payload) {
            state.test = payload
        }
    },
});

now you need to add this store to your main vue instance:

import Vue from 'vue'

Vue.use(Vuex);

let vm = new Vue({
    el: '#app',
    store,
    // ...
});

all done. now in every component you can access the states by this.$store.state. for making life easier, you can define a computed variable like this:

computed: {
    test() {
        return this.$store.state.test
    }
}

to change the state you just need to commit the setTest mutation. you have to add this mutation to methods and simply call it like this:

methods: {
    ...Vuex.mapMutations(['setTest']),
    myMethod() {
        // do this

        this.setTest('some value');

        // do that
    }
}

you can also make a global mixin like i told you before to add this computed and mutation to every instance like this: (add this before make the main vue instance)

Vue.mixin({
    computed: {
        test() {
            return this.$store.state.test
        }
    },
    methods: {
        ...Vuex.mapMutations(['setTest']),
    }
});

but i don't recommend to do this because when the project grow big, it gets so hard to avoid name confusion. it's better to make them separately for each component to chose proper names.

Upvotes: 1

Mehdi
Mehdi

Reputation: 756

you can use mixin method on main Vue instance like this:

import Vue from 'vue'
import MyMixin from './mixins.js'

Vue.mixin(MyMixin);

It will apply this mixin for all instance no matter how deep they are.

Upvotes: 0

Related Questions