1.使用同一数据源(store)的组件放在一个目录中
2.根组件(index.vue)中引用store,子组件不引用
export default { name:'Counter1', methods:{ localMethod() { }, //updateCount(value) { this.$store.commit('UPDATE_COUNT', value) }, ...mapActions({increment:'incrementCounter', decrement:'decrementCounter'}), ...mapActions(['GetRsakey']) }, computed:{ s:{get() {return this.$store.state}}, //简化 //扩展运算符( spread )是三个点(...)。它好比rest参数的逆运算,将一个数组转为用逗号分隔的参数序列。 ...mapGetters({ counterValue: 'getCount',ccc:'getCount2' }), count:{ get() {return this.$store.state.count}, set(val) {this.$store.commit('UPDATE_COUNT', val)} } } ,store }
3.store写法
import Vue from 'vue' import Vuex from 'vuex' import * as actions from './actions' import * as getters from './getters' // 告诉 vue “使用” vuex Vue.use(Vuex) const state = { count: 100, key:'', uid:'test', pwd:'1' } const mutations = { INCREMENT (state,n) { state.count+=n }, DECREMENT (state,n) { state.count-=n }, UPDATE_COUNT(state,n){ state.count=parseInt(n) }, setKey:(state,k)=>state.key=k } export default new Vuex.Store({ state, //数据 getters, //读取时进行转换(compute),不转换的数据可以在vue中直接用{{this.$store.state.xxx}}读取 actions, //设置时提交改变(commit) mutations //操作 })
4.action写法
import {Ajax} from './api/Ajax' import {RSAKeyPair,encryptedString} from './api/RSA' import {setMaxDigits} from './api/RSA/BigInt' //新版用commit(vuex会把commit和state传进来) export const incrementCounter = ({ commit,state }) => { commit('INCREMENT', 10); //调用INCREMENT方法,后面跟参数 } export const decrementCounter = ({ commit,state }) => { commit('DECREMENT', 10); //调用DECREMENT方法,后面跟参数 } export const GetRsakey=({ commit,state })=> { Ajax.post("GetRsakey",{ver:'json'}).then((r)=> { //console.log(r.data.RsaXMLPublicKey); commit('setKey', r.data.RsaXMLPublicKey); setMaxDigits(131); let pair = r.data.RsaXMLPublicKey.split(","); let key = new RSAKeyPair(pair[0], "", pair[1]); let data = {}; data.UserName = encryptedString(key, state.uid); data.UserPWD = encryptedString(key, state.pwd); data.OEAP = false; Ajax.post("Login",data).then((r)=> { console.log(r.data); }); }); } /*参考 export const addToCart = ({ commit }, product) => { if (product.inventory > 0) { commit(types.ADD_TO_CART, { id: product.id }) } } */
5.getter写法
// 这个 getter 函数会返回 count 的值 // 在 ES6 里你可以写成: // export const getCount = state => state.count export function getCount (state) { return state.count+"次"; } export function getCount2 (state) { return state.count; }