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:
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"
This is our .babelrc
configuration file:
{
"presets": ["@vue/babel-preset-jsx"]
}
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"
}
]
}
}
This is our index.html
under src
folder:
<!DOCTYPE html>
<html>
<head>
<title>happiness</title>
</head>
<body>
<div id='app'></div>
</body>
</html>
And this the main.js
file:
import App from './components/app'
new App({
el:'#app'
})
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>
)
}
})
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)
}
}
})
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
}
}
})
Top comments (0)