简单粗暴地使用Vuex(一)

Vuex的使用

  • 在src下新建一个store文件夹,下面建一个index.js
  • 在main.js中使用import store from './store/index.js',并在vue实例中挂载stroe
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
  • index.js中的文件内容为
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {

  },
  actions: {

  },
  mutations: {

  },
  actions: {

  }
})
  • state中存储的就是公共的数据
  • 在页面中使用公共数据直接使用{{this.$store.state.name}}
  • 修改store中的数据,必须经过actions,mutations,如果没有异步操作及批量处理,也可以省略actions,直接使用mutations来提交数据
  • 提交actions时接受两个参数,一个是ctx上下文,一个是修改的state数据
  • 使用this.$store.dispatch('changeName',newName)
  • 在dispatch的changeName中如何提交mutations呢?使用ctx.commit('changeName',newName)
  • mutations的changeName方法中接受两个参数(state,newName),在mutations中使用state.name = newName,即可修改
  • 看一个例子,切换Home.vue组件中的国家名
//Home.vue
<template>
  <div class="home">
    <p>这里显示store里面的name:{{this.$store.state.name}}</p>
    <button @click="changeCity">点击切换</button>
  </div>
</template>

<script>

export default {
  name: 'Home',
  methods: {
    changeCity () {
      this.$store.dispatch('changeCity','美国')
    }
  }
}
</script>
***********************
//store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    name: '中国'
  },
  mutations: {
    changeCity (state, newCity) {
      state.name = newCity
    }
  },
  actions: {
    changeCity (ctx, newCity) {
      ctx.commit('changeCity',newCity)
    }
  }
})
  • 如果actions中没有过于复杂的操作或异步操作,也可以直接在点击事件方法中使用this.$store.commit提交mutations,即跳过actions
//Home.vue
<template>
  <div class="home">
    <p>这里显示store里面的name:{{this.$store.state.name}}</p>
    <button @click="changeCity">点击切换</button>
  </div>
</template>

<script>

export default {
  name: 'Home',
  methods: {
    changeCity () {
      this.$store.commit('changeCity','美国')
    }
  }
}
  • 在页面中引用vuex中的数据时,使用的是{{this.$store.state.name}},可以使用...mapState进行简化
  • ...mapMutations可以简化提交commit的mutations
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容