mpvue - 使用vuex

    前提:在mpvue安装了vuex

使用:

    1)创建store/index.js

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

export default new Vuex.Store({
  state: {
    address: ''
  },
  mutations: {
    setAddress (state, newAddress) {
      state.address = newAddress
    }
  },
  actions: {
    setAddress ({ commit }, newAddress) {
      commit('setAddress', newAddress)
    }
  }
})

    2)使用:
    方法一:

// 导入store
import store from '../../store'
//在方法中调用
cityChoose (name) {
  store.commit('setAddress', name)
  //或者是
  store.dispatch('setAddress', name)
}

    方法二:
        使用vuex辅助函数
        注意小程序以多页形式渲染,故每个页面都需要创建vue实例并引入相应的store模块
        在pages中的main.js导入vuex和store

import Vue from 'vue'
import Vuex from 'vuex'
import App from './index'
import store from '../../store'
Vue.use(Vuex)
// 重要,否则会出现辅助函数不能使用问题
Vue.prototype.$store = store
const app = new Vue({
  ...App,
  store
})
app.$mount()

在页面中的使用
import { mapActions } from 'vuex'

methods: {
  ...mapActions(['setAddress']),
  cityChoose (name) {
    this.setAddress(name)
  }
}

vuex module模块使用

    在store/modules新建app.js

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

export default {
  namespaced: true,
  state: {
    address: ''
  },
  mutations: {
    setAddress (state, newAddress) {
      state.address = newAddress
    }
  },
  actions: {
    setAddress ({ commit }, newAddress) {
      commit('setAddress', newAddress)
    }
  }
}

    在index.js中使用

import Vue from 'vue'
import Vuex from 'vuex'
import app from './module/app'
Vue.use(Vuex)

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

使用

在main.js中

import store from '../../store'
// 重要,否则会出现辅助函数不能使用问题
Vue.prototype.$store = store

在使用页面中

import { mapState, mapActions } from 'vuex'

computed: {
  ...mapState('app', ['address'])
},
methods: {
  ...mapActions('app', ['setAddress']),
  cityChoose (name) {
    this.setAddress(name)
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值