本文学习自jspang的博客和b站视频 首页 | 技术胖-胜洪宇关注web前端技术-前端免费视频第一博客
一.state里写data数据和prop属性
store写法
const state={
count:1
}
html写法
先在script里引入store文件
1.渲染store 的state里的数据
<div> {{$store.state.count}} </div>
通过三种方式将html的写法改变成下面这种
<div> {{count}} </div>
one
computed:mapState({
count:state=>state.count
})
two
computed:mapState(["count"])
there
...mapstate(["count"])
二.mutation里写改变(状态)数据的方法
store写法
const mutations={
add(state){
state.count++;
},
reduce(state){
state.count--;
}
}
HTML写法
调用store的mutation里的方法
commit即提交什么方法的意思
<button @click="$store.commit('add')">+</button>
在mutation传递参数并在html渲染
store
const mutations={
add(state,n){
state.count+=n;
},
reduce(state){
state.count--;
}
}
html
<p>
<button @click="$store.commit('add',10)">+</button>
<button @click="$store.commit('reduce')">-</button>
</p>
将上面的方法转换成下面的这种写法,即去除$store.commit
<button @click="reduce">-</button>
方法
methods:mapMutations([
'add','reduce'
]),
三.getters计算过滤操作 (相当于html页面的compute)
store写法
const getters = {
count:function(state){
return state.count +=10;
}
}
在html用getters里的方法
computed:{
...mapState(["count"]),
...mapGetters(["count"])
},
四.actions异步修改状态
store写法
const actions ={
addAction(context){
context.commit('add',10)
},
reduceAction({commit}){
commit('reduce')
}
}
HTML写法
<p>
<button @click="addAction">+</button>
<button @click="reduceAction">-</button>
</p>
methods:{
...mapMutations([
'add','reduce'
]),
...mapActions(['addAction','reduceAction'])
},