使用vuex实现数据共享

使用vuex实现数据共享

在这里插入图片描述

·Actions:异步操作;Mutations:同步操作;state:存储公用数据
·组件调用Dispatch方法来调用Action进行异步操作,组件或Actions调用Commit方法来调用Mutations进行同步操作,从而改变state里面的值

如何使用vuex
1、安装vuex

npm
npm install vuex --save

2、引用vuex

import Vue from 'vue'
import Vuex from 'vuex'
//vuex为插件,vue中使用vuex用vue.use()
Vue.use(Vuex)

3、因为vuex比较复杂,可以单独新建一个js文件

store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)


//new Vuex.Store 新建一个仓库
export default new Vuex.Store({
  state: {
      //公用数据 列如:city: '北京'
      timed: '00:00:20',
      judge: 0
  },
  
  actions: {
  // ctx 上下文 可以调用commit这个方法
    changeTime (ctx, item) {
    // commit:同步操作,写法:this.$store.commit('mutations方法名',值)
    //调用mutations里面的方法
      ctx.commit('changeTime', item)
    }
  },
  mutations: {
    changeTime (state, item) {
      console.log(item.timed, item.judge, 'juuu')
      //将传入的值赋值给state里的值
      state.timed = item.timed
      state.judge = item.judge
    }
  }
})

4、在main.js中引入该文件

import store from './store'

//创建实例时,将store传入
new Vue({
    store: store
})

5、在页面上引用

//引用store里的state里的city
<div>{{this.$store.state.timed}}</div>

6、改变公共数据

//在需要改变的页面中写这个方法,通过该方法改变共用的值
handleTime (item) {
    // dispatch:含有异步操作,例如向后台提交数据,
    //写法: this.$store.dispatch('action方法名',传入的值)
    this.$store.dispatch('changeTime', item)
}

7、当没有异步操作时,可直接调用commit方法

handleTime (item) {
    //写法: this.$store.commit('mutations方法名',传入的值)
    this.$store.commit('changeTime', item)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值