用store 模拟记住密码功能 VUE

 register.vue

<template>
  <div>
    <h3>Register</h3>Name:
    <input type="text" v-model="a">
    <br>Password:
    <input type="password" v-model="b">
    <br>sumbit:
    <input type="submit">
  </div>
</template> 

<script>
import Vue from "vue";
import Vuex, { mapState, mapActions } from "vuex";
import UserModule from "./store/index";

export default {
  data() {
    return {
};
  },
  created() {
    //使用vuex
    Vue.use(Vuex);
    //创建一个store对象
    this.$store = new Vuex.Store();
    //注册路由模块,叫user
    this.$store.registerModule("USER", UserModule);
    // 怎么不能调用
    this.getUserAction()
    // this.store.dispatch('USER/getUserAction')

  },
  methods: {
    //映射的请求函数是getUserAction
    ...mapActions("USER", ["getUserAction"])
  },
  //把可能经常变动的值放在这,对应state.js(默认值)
  computed: {
    ...mapState("USER", {
      a: state => state.a,
      b: state => state.b
    }),

  }
};
</script>

index.js


import UserState from '../store/state'
import UserAction from '../store/action'
import UserMutation from '../store/mutation'

const UserStore = {
    namespaced: true,
    state: UserState,
    actions: UserAction,
    mutations: UserMutation,
}


export default UserStore

action.js 

//模拟ajax请求,直接返回值
const UserAction={
    getUserAction(store){
        let data={
            a:1,
            b:2
        }
//数据存在COMMITUSER
        store.commit('COMMITUSER',data)
        
    }
}
export default UserAction

mutation.js

const UserMutation = {
  //数据存在这

    COMMITUSER(state, data = {}) {
        state.a = data.a
        state.b = data.b
        console.log(state)
    },

}
export default UserMutation

state.js

//设置默认值
class UserState {
    defaultState() {
        return {
            a:"",
            b:""
        }
    }
}
export default new UserState().defaultState()

猜你喜欢

转载自blog.csdn.net/XYLHxylh/article/details/86140284