uniapp 使用vuex
根目录新建 store目录,再store下新建index.js
import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
const Store = new Vuex.Store({
state:{
giftList:[]
},
getters:{},
mutations:{
SET_GIFT:(state,payload)=>state.giftList = payload
},
actions:{},
modules:{}
})
export default Store
在main.js引入store
import store from "./store/index.js"
Vue.prototype.$store = store
const app = new Vue({
store,
...App
})
在A组件给gift赋值
import { mapState, mapMutations } from 'vuex'
//取giftList
computed: {
...mapState(['giftList']),
},
methods:{
...mapMutations(['SET_GIFT']), //引入store方法
//给giftList赋值
onGift(){
let data = {
name: '代代',
id: 1
}
const arr = [...this.giftList,data]
this.SET_GIFT(arr)
}
}
在B组件获取giftList
<view>{{giftList}}</view>
import { mapState } from 'vuex'
computed: {
...mapState(['giftList'])
}