DEV Community

Cover image for Vuex explained through PHP
Mati Andreas
Mati Andreas

Posted on

Vuex explained through PHP

Vue.js was not around when I and many other developers started to code years ago. Even jQuery was just released. And if you have been using jQuery in front-end as a (PHP backend) developer, understanding all the aspects of Vuex flow could be tricky.

Let's see first this example from real 2007 code, still in production:

$myrow = mysql_fetch_array(mysql_query(
    "select * from albums where number LIKE '"
    . mysql_real_escape_string($_GET['number']) . "'"
));
echo '<b>' . stripslashes($myrow["number"])
    . ' album &#39;' . stripslashes($myrow["name"]) . '&#39;</b>';
Enter fullscreen mode Exit fullscreen mode

In simple PHP page, data is taken from database and printed out.

Now let's try to write it in Vuex + Vue component like flow in PHP:

# VUEX
$GLOBALS['state']['album_data'] = null;

function actionLoadCurrentAlbum(string $number): void
{
    ## Backend API call
    $myrow = mysql_fetch_array(mysql_query(
        "select * from albums where number LIKE '"
        . mysql_real_escape_string($number) . "'"
    ));
    mutationCurrentAlbum($myrow);
}

function mutationCurrentAlbum(?array $albumData): void
{
    $GLOBALS['state']['album_data'] = $albumData;
}

function getCurrentAlbum(): ?array
{
    return $GLOBALS['state']['album_data'];
}

# Vue Component
## Script
actionLoadCurrentAlbum($_GET['number']);
$albumData = getCurrentAlbum();
## template
echo '<b>' . stripslashes($albumData['name']) . ' album &#39;' 
    . stripslashes($albumData['number']) . '&#39;</b>';
Enter fullscreen mode Exit fullscreen mode

And in JavaScript as Vuex and Vue component

new Vuex.Store({
    state: {
        album_data: null
    },
    actions: {
        async loadCurrentAlbum(context, number) {
            const url = `https://example.com/some/path/${number}`
            let response = await (await fetch(url)).json()
            context.commit('setCurrentAlbum', response)
        }
    },
    mutations: {
        setCurrentAlbum(state, albumData) {
            state.album_data = albumData
        }
    },
    getters: {
        getCurrentAlbum: state => {
            return state.album_data
        }
    }
})

Vue.component('album', {
    beforeCreate: function() {
        this.$state.dispatch('loadCurrentAlbum',
            this.$route.params.number)
    },
    computed: mapState([
        'album_data'
    ]),
    template:
        '<b>{{ album_data.name }} album '
        + '&#39;{{ album_data.number }}&#39;</b>'
})
Enter fullscreen mode Exit fullscreen mode

Now we have Vuex example translated from year 2007 PHP page.

Top comments (0)