vuex
可以大范围传值,维护一个大的共享变量store。可以直接用全局变量store
,其他组件直接使用store
就行。vuex步骤
在组件中访问State的方式:
this.$store.state.
全局数据名称 如:this.$store.state.countimport { mapState } from 'vuex'
computed:{ ...mapState(['全局数据名称']) }
methods:{
btnHander(){
this.$store.state.count++;
}
//store/index.js
mutations: {
add(state,step){
//第一个形参永远都是state也就是$state对象
//第二个形参是调用add时传递的参数
state.count+=step;
}
}
<button @click="Add">+1</button>
//app.vue
methods:{
Add(){
//使用commit函数调用mutations中的对应函数,
//第一个参数就是我们要调用的mutations中的函数名
//第二个参数就是传递给add函数的参数
this.$store.commit('add',10)
}
}
正确的修改store里属性
使用mutations的第二种方式:
// store.mutations
mutations: {
add(state,n){
//变更状态
state.count+=n;
},
sub(state){
state.count--;
}
},
//============
<script>
import {mapState,mapMutations} from 'vuex'
export default{
data(){
return{};
},
methods: {
...mapMutations(['sub']),
btnhand2(){
this.sub();
}
},
}
</script>
actions: {
addAsync(context,step){
setTimeout(()=>{
context.commit('add',step);
},2000)
}
}
<button @click="AddAsync">...+1</button>
methods:{
AddAsync(){
this.$store.dispatch('addAsync',5)
}
}
第二种方式:
import { mapState,mapMutations,mapActions } from ‘vuex’
export default {
data() {
return {}
},
methods:{
//获得mapMutations映射的sub函数
...mapMutations(['sub']),
//当点击按钮时触发Sub函数
Sub(){
//调用sub函数完成对数据的操作
this.sub(10);
},
//获得mapActions映射的addAsync函数
...mapActions(['subAsync']),
asyncSub(){
this.subAsync(5);
}
},
computed:{
...mapState(['count'])
}
}
不会修改
,只起到包装的作用,类似于计算属性。
并不会修改Store中保存的数据
,当Store中的数据发生变化时,Getter生成的内容也会随之变化
export default new Vuex.Store({
getters:{
//添加了一个showNum的属性
showNum : state =>{
return '最新的count值为:'+state.count;
}
}
})
<h3>{{$store.getters.showNum}}</h3>
//或者也可以在Addition.vue中,导入mapGetters,并将之映射为计算属性
import { mapGetters } from 'vuex'
computed:{
...mapGetters(['showNum'])
}
因篇幅问题不能全部显示,请点此查看更多更全内容