Tuesday, March 30, 2021

Vuex

 

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const url = "https://icanhazdadjoke.com";
const headers = { Accept: "application/json" };
export default new Vuex.Store({
state: {
currentJoke: "This is a joke",
allJokes: []
},
mutations: {
//syncrous
setCurrentJoke(state, payload) {
state.currentJoke = payload;
state.allJokes.push(payload);
}
},
actions: {
//asyncronous
async setCurrentJoke(state) {
const joke = await fetch(url, { headers });
const j = await joke.json();
state.commit("setCurrentJoke", j.joke);
}
},
modules: {},
getters: {
getCurrentJoke: state => state.currentJoke,
getAllJokes: state => state.allJokes
}
});
<template>
<div class="home shadow-xl bg-gray-200 w-8/12 mx-auto p-20">
<h2 class="text-3xl text-blue-600 font-extrabold">Can I Haz Dad Jokes</h2>
<h3 class="h-40 text-black">{{joke}}</h3>
<button
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full mt-10 focus:outline-none"
@click="addJoke"
>Add Joke</button>
</div>
</template>
<script>
// @ is an alias to /src
import { mapActions, mapGetters } from "vuex";
export default {
name: "Home",
methods: {
...mapActions({ addJoke: "setCurrentJoke" })
// addJoke() {
// this.$store.dispatch("setCurrentJoke");
// this.setCurrentJoke();
// }
},
computed: {
...mapGetters({ joke: "getCurrentJoke" })
// joke() {
// return this.getCurrentJoke;
// }
}
// mounted() {
// this.joke = this.$store.getters.getCurrentJoke;
// }
};
</script>
<style scoped>
.home {
height: 400px;
max-height: 500px;
}
h3 {
font-size: 2.5rem;
}
</style>

laravel mix - lazy loading Vue components

STEP:1

Run this following command

*npm install --save-dev babel-plugin-dynamic-import-webpack

*npm install --save-dev babel-plugin-syntax-dynamic-import


STEP:2

Create a file in the root of your Laravel application called .babelrc with the following contents.


{

    "plugins": ["syntax-dynamic-import"]

}


STEP:3

Update your webpack.mix.js file to the following:


let mix = require('laravel-mix');


// Override mix internal webpack output configuration

mix.config.webpackConfig.output = {

    chunkFilename: 'js/pages/[name].bundle.js',

    publicPath: '/',

};


STEP:4

Instead of loading components in the standard way,


Vue.component(

    'example-component',

    require('./components/ExampleComponent.vue') 

);


We need to use the lazy loading import method.


Vue.component(

    'example-component', 

    () => import(

        /* webpackChunkName: "example-component" */

        './components/ExampleComponent.vue'

    )

);


Ref:https://acode.ninja/posts/laravel-mix-lazy-loading-vue-components/