Vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension (opens new window),提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。

export default new Vuex.Store({
    state: {
    carName:'玛莎拉蒂',
    carPrice:'100w',
    carAdrees:'意大利',
    phone:[]
  },
  //定义计算属性
  getters:{
    carinfo(state){
      return `汽车名称:${state.carName},汽车价格:${state.carPrice},汽车产地:${state.carAdrees}`
    },
    totalPrice(state){
      return state.phone.map(r=>r.price).reduce((a,b)=>a+b,0)
    }
  },
  mutations: {
    updateCarName(state,val){
      state.carName=val
    },
    updateCarPrice(state,val){
      state.carPrice=val
    },
    updateCarAddress(state,val){
      state.carAdrees=val
    },
    loadPhone(state,val){
      state.phone=val
    },
    addphone(state,val){
      state.phone.push(val)
    }
  },
  actions: {
    //定义一个方法,可以是异步的,官方定义是在mutations中在定义一个方法来修改数据
    updateCarAddress(store,val){
      axios.get(val)
      .then(({data}) => {
        store.commit('updateCarAddress',data.address)
      })
  },
    loadPhone(store,val){
      axios.get(val)
      .then(({data}) => {
        console.log(data);
        store.commit('loadPhone',data)
      })
    }
},
  modules: {
  }
})

state:驱动应用的数据源;
getters:定义计算属性
mutations:定义方法(同步)
actions:定义方法,方法可以是异步的,官方定义是在mutations中在定义一个方法来修改数据

getters

定义计算属性,参数是state

 carinfo(state){
      return `汽车名称:${state.carName},汽车价格:${state.carPrice},汽车产地:${state.carAdrees}`
    },

用法:在页面的计算属性中简化代码量

carinfo(){
      return this.$store.getters.carinfo
    }
<div>{{carinfo}}</div>

mutations

定义方法,定义的方法是同步的,方法有两个参数,分别是stateval
state是当前定义的值,val是修改的值

updateCarName(state,val){
      state.carName=val
    },

使用mutations中定义的方法格式 $store.commit('方法名',‘’修改的值)
行内写法格式

 <button @click="$store.commit('updateCarName','保时捷')">修改汽车名称</button>

点击事件updateCarName

 updateCarName(){
      this.$store.commit('updateCarName','保时捷')
    },

actions

actions中定义的方法是可以异步的,官方推荐数据的修改使用mutations中的方法进行修改
actions中定义的方法的两个参数分别是storeval
mutations 中定义的方法

    updateCarAddress(state,val){
      state.carAdrees=val
    },

actions 中定义的方法

    updateCarAddress(store,val){
      axios.get(val)
      .then(({data}) => {
        store.commit('updateCarAddress',data.address)
      })

methods 中定义的方法

    //通过actions来调用方法,可以是异步的
点击事件
    updateCaraddress(){
    点击触发actions 中的方法 updateCarAddress 传值
      this.$store.dispatch('updateCarAddress', 'data/data.json')
    }

mutations中的方法调用的格式
·this.$store.commit(' 方法名','修改的值')
actions 中定义的方法调用的格式
this.$store.dispatch('方法名','传值')

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容