001_Vue核心插件_vuex

001_Vue核心插件_vuex(h3)

  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
  • \src\main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store/index'

Vue.config.productionTip = false

new Vue({
  store,
  render: h => h(App)
}).$mount('#app')

  • \src\App.vue
<template>
  <div id="app"><m-parent></m-parent></div>
</template>

<style></style>

<script>
import MParent from './views/Home'
export default {
  data() {
    return {}
  },
  components: {
    MParent
  },
  methods: {}
}
</script>

  • \src\views\Home.vue
<template>
  <div>
    <button @click="add_dl">增加</button>
    <h5>
      vuex <span style="color: red">{{ count_dl }}</span>
      <h5>
        getters <span style="color: red">{{ doubleCount }}</span>
      </h5>
    </h5>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
export default {
  // computed: {
  //   count_dl() {
  //     return this.$store.state.count
  //   },
  //   doubleCount() {
  //     return this.$store.getters.doubleCount
  //   }
  // },
  //辅助函数
  computed: {
    // ...mapState({
    //   //等同于 count =>state.count
    //   count_dl: 'count'
    // }),
    //模块化后上面取不到值
    ...mapState({
      count_dl: state => state.text.count
    }),
    ...mapGetters(['doubleCount'])
  },
  methods: {
    add_dl() {
      //在组件中使用 this.$store.commit('xxx') 调用 mutations
      this.$store.commit('add')
      //在组件中使用 this.$store.dispatch('xxx') 分发 action
      //this.$store.dispatch('delayAdd')
    }
  }
}
</script>

<style lang="scss" scoped></style>

  • \src\store\index.js
import Vue from 'vue'
import Vuex from 'vuex'
import text from './text'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    text
  }
})

  • \src\store\text.js
export default {
  //option_1 唯一数据源 
  state: {
    count: 0,
  },
  //option_2 store的计算属性 
  getters: {
    doubleCount(state) {
      return state.count * 2
    }
  },
  //option_3 更改Vuex的store中的状态的唯一方法
  mutations: {
    add(state) {
      state.count ++
    },
    decrease(state) {
      state.count --
    }
  },
  //option_3 Action提交的是mutation,而不是直接变更状态;可以包含任意异步操作。
  actions: {
    delayAdd(context) {
      setTimeout(() => {
        //调用 context.commit 提交一个 mutation
        context.commit('add')
      }, 1000);
    }
  }
}
  • 浏览器界面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值