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 '' . stripslashes($myrow["name"]) . ''</b>';
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 ''
. stripslashes($albumData['number']) . ''</b>';
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 '
+ ''{{ album_data.number }}'</b>'
})
Top comments (0)