DEV Community

roggc
roggc

Posted on • Updated on

Managing state in Vue.js

After reading this post I came up with this implementation for state management.
To show it to you, I will develop a hello world app with Vue.
This is the folder structure:
Alt Text
These are the dependencies (what we must install):

    "@babel/core": "^7.8.3",
    "@vue/babel-helper-vue-jsx-merge-props": "^1.0.0",
    "@vue/babel-preset-jsx": "^1.1.2",
    "babel-loader": "^8.0.6",
    "html-webpack-plugin": "^3.2.0",
    "vue": "^2.6.11",
    "vue-styled-components": "^1.4.14",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.1"
Enter fullscreen mode Exit fullscreen mode

This is our .babelrc configuration file:

{
    "presets": ["@vue/babel-preset-jsx"]
  }
Enter fullscreen mode Exit fullscreen mode

And this is the webpack.config.js configuration file:

const HtmlWebpackPlugin=require('html-webpack-plugin')

module.exports={
    entry:'./src/main.js',
    plugins:[
        new HtmlWebpackPlugin({
            template:'src/index.html'
        })
    ],
  module: {
    rules: [
      {
        test: /\.js?$/,
        loader: "babel-loader"
      }
    ]
}
}
Enter fullscreen mode Exit fullscreen mode

This is our index.html under src folder:

<!DOCTYPE html>
<html>
    <head>
        <title>happiness</title>
    </head>
    <body>
        <div id='app'></div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

And this the main.js file:

import App from './components/app'

new App({
    el:'#app'
})
Enter fullscreen mode Exit fullscreen mode

This is the app.js file in src/components folder:

import Vue from 'vue'
import s from 'vue-styled-components'
import Happiness from '../state/happiness'

export default Vue.extend({
    name:'myApp',
    data(){
        return{
            myHappiness:new Happiness()
        }
    },
    render(){
        const Div=s.div`
        font-family:sans-serif;
        `
        const myHappiness=this.myHappiness
        myHappiness.commit({type:'init'})
        return(
            <Div>I am {myHappiness.state.value}</Div>
        )
    }
})
Enter fullscreen mode Exit fullscreen mode

This is the withState.js file in src/state folder:

import Vue from 'vue'

export default mutations=>
Vue.extend({
    data(){
        return{
            state:null
        }
    },
   methods:{
       commit(data){
           mutations[data.type](data,this)
       }
   } 
})
Enter fullscreen mode Exit fullscreen mode

And this is the happiness.js file in src/state folder:

import withState from './withState'

export default withState({
    init(data,this_){
        if(this_.state===null){
            this_.state={
                value:'😄'
            }
        }
    },
    setState(data,this_){
        this_.state={
            ...this_.state,
            ...data.val
        }
    }
})
Enter fullscreen mode Exit fullscreen mode

And this is the final result:
Alt Text

Top comments (0)