vuex

//   /store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    counter:1000
  },
  mutations: {
    //方法 默认传入state参数
    increment(state){
      state.counter++
    },
    decrement(state){
      state.counter--
    }
  },
  actions: {
  },
  modules: {
  }
})
// App.vue

<template>
  <div id="app">
    <h2>{{$store.state.counter}}</h2>
    <hr>
    <hello-world/>
    <button @click="addition">+</button>
    <button @click="subtract">-</button>
  </div>
</template>
<script>
import HelloWorld from './components/HelloWorld';


export default {
  name:'App',
  components:{
    HelloWorld
  },
  methods:{
    addition(){
      this.$store.commit('increment')
    },
    subtract(){
      this.$store.commit('decrement')
    }
  }
}
</script>
<style>
 
</style>
// HelloWorld.vue

<template>
  <div>
    <h2>{{$store.state.counter}}</h2>
  </div>
</template>

<script>
export default {
  name:'HelloWorld',
}
</script>
  • store
    1.getter
getters:{
    powerCounter(state){
      return state.counter * state.counter
    },
    above20Stu(state){
      return state.students.filter(item => item.age > 20)
    },
    //第二个参数是getters
    above20StuLength(state,getters){
      return getters.above20Stu.length
    },
    aboveAge(state){
      // return function(age){
      //   return state.students.filter(item => item.age > age)
      // }
      //接收参数
      return age =>{
        return state.students.filter(item => item.age > age)
      }
    }
  },

2.vuex 的store状态的更新的唯一方式:提交Mutation

addByCount(count){
   // this.$store.commit('incrementByCount',count)
   // 另一种提交风格
   this.$store.commit({
     type:'incrementByCount',
     count,
   })
 },
incrementByCount(state,payload){
   state.counter+=payload.count
  },
  • Vuex 的store中的state是响应式的,当state中的数据发生改变时,vue组件会自动更新
    我们必须遵守一些vuex对应的规则:
    • 提前在store中初始化好所需的属性,更改属性会刷新,后来新加的并不会刷新(响应式)
    • Vue.set(要新增或修改的对象或数组,对象key或索引值,新值)
    • delete state.info.age 这种删除对象属性的方式不是响应式的
    • Vue.delete(state.info, age)
  • 不要再Mutation进行异步操作,用Action来替代
//App.vue
updateInfo(){ 
  this.$store.dispatch('aUpdateInfo')
 }
// /store/index.js
mutation:{
	updateInfo(state) {
      state.info.name = 'zjh'
    }
}
//异步操作
 actions: {
   //context相当于store
   aUpdateInfo(context,payload) {
     setTimeout(() =>{
       context.commit('updateInfo')
     },1000)
   }
  },

modules中的actions里的context.commit是指本modules的mutations而不是store中的mutations

<script>
  const obj = {name:'kobe',age:14}
  // const name = obj.name;
  // const age = obj.age;

  // 另一种写法:对象的解构
  // age,name顺序可以换,因为他是按照名字的
  const {age,name} = obj;
  console.log(name);
  console.log(age);

</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值