vuex的使用杂录

写在前:vue官方文档 地址


定义:Vuex是一个专为Vue.js应用程序开发的状态管理模式。

范围:组件之间共享的数据。


安装vuex

npm install vuex --save

引入:

import Vuex from 'vuex'
Vue.use(Vuex)

创建store对象

const store = new Vuex.Store({
  state:{count: 0},
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {

  }
})

//state 数据源

//mutations  同步方法集合

// actions 异步方法集合

// 如果想要改变state中的数据必须在mutations  actions  中修改

挂载到vue实例中

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

vuex的核心概念:

1.数据源state 

{{$store.state.count}}直接使用
// 引入
import { mapState} from 'vuex'

// 辅助函数
  computed: {
    ...mapState(['count'])
  },

//使用
{{count}}

2.通过mutation变更 store 数据

export default new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    add (state) {
      state.count++
    }
  },
  actions: {}
})

使用页面:

  methods: {
    addnumber () {
      this.$store.commit('add')
    }
  }

重点:this.$store.commit('add')   (使用commit 触发 mutations中的方法)

注:mutations 是同步的方法   actions 是异步得方法,调用mutations 中的方法

  actions: {
    addAsync (context, step) {
      setTimeout(() => {
        context.commit('add', step)
      }, 1000)
    }
  }

使用 actions 中的函数

在methods中
    subaycy () {
      this.$store.dispatch('addAsync', 5)
    }

另一种方式:

import { mapState, mapMutations, mapActions } from 'vuex'
  methods: {
    ...mapMutations(['sub']),
    ...mapActions(['addAsync'])
    // subnumber () {
    //   this.sub()
    // },
    subaycy () {
      this.addAsync(5)
    }
  }

 


3.getters(包装state 中的数据)

  getters: {
    doneTodes: state => {
      return '这是最新的count值【' + state.count +'】'
    }
  }
// 使用
{{$store.getters.doneTodes}}
// 另一中使用方式
//使用:
{{doneTodes}}

//引入
import { mapGetters } from 'vuex'
// 辅助函数
computed: {
    ...mapGetters(['doneTodes'])
},

注:小范围数据使用:

父向子传值: v-bind 属性绑定

子向父传值: v-on 事件绑定

兄弟组件之间共享数据: EventBus

$on  接收数据的那个组件

$emit  发送数据的那个组件

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值