Vuex{{this.$store.state.city}}

异步操作放在actions里面 或者说是 批量的同步操作也放在actions里面

actions需要用commit来调用mutation

cnpm install vuex --save

 创建store目录并在store目录下创建index.js

在main.js入口文件中引入,加入store

export default new Vuex.Store({
  state:{
    city : "天下"
  },
  actions:{
    changeCity(ctx,city){
      ctx.commit('changeCity',city)
    }
  },
  mutations:{
    changeCity(state,city){
      state.city = city
    }
  },
})
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

获取state的值

{{this.$store.state.city}}

state语法糖

    import {mapState} from 'vuex'

    computed:{
      ...mapState(['city'])
    }

调用actions

this.$store.dispatch('changeCity',city)

若没有actions的话直接使用commit来调用mutations

this.$store.commit('changeCity',city)

猜你喜欢

转载自blog.csdn.net/aoxue018/article/details/81153724
今日推荐