vue3-cookies vuex

VUe.use(VueCookies)

import VueCookies from 'vue3-cookies'

 this.$cookies.set('userId', res.id, '1M')

-----------------------------------------------------------------------------------------------------------

vuex 用法

1.Vue.use(Vuex)  绑定全局

2.src>store>index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
    username: '', // 登录用0
    cartCount: 0 // 购物车商品数量
  },
  mutations: {
    saveUserName (state, username) {
      state.username = username
    },
    saveCartCount (state, count) {
      state.cartCount = count
    }
  },
  actions: {
    saveUserName (context, username) {
      context.commit('saveUserName', username)
    },
    saveCartCount (context, count) {
      context.commit('saveCartCount', count)
    }
  }
})

3.在login.vue 中调用

export default {
  name: 'login',
  components: {
    NavFooter
  },
  data () {
    return {
      username: '',
      password: '',
      userId: ''
    }
  },
  methods: {
    login () {
      const { username, password } = this
      if (!username || !password) {
         this.$message.error('请输入正确的用户名和密码')
        return
      }
      this.axios.post('/user/login', {
        username,
        password
      }).then((res) => {
        this.$cookies.set('userId', res.id, '1M')
        this.$store.dispatch('saveUserName', res.username)
        this.$router.push('/index')
      //   this.saveUserName(res.username)  es6

    },
    // ...mapActions(['saveUserName']),  es6  引入mapActions
   
    }
  }
}

4.0要改变值的vue

 computed: {
    userName () {
      return this.$store.state.username
    },
    cartCount () {
      return this.$store.state.cartCount
    }
    // ...mapActions(['username','cartCount']),  es6
  },

html


      

5.获取用户信息app.vue   防止用户刷新重新拉去数据

export default {
  name: 'app',
  data () {
    return {

    }
  },
  mounted () {
    this.getUser()
    this.getCartCount()
  },
  methods: {
    getUser () {
      this.axios.get('/user').then((res) => {
        // to-do 保存到vuex里面
        this.$store.dispatch('saveUserName', res.username)
      })
    },
    getCartCount () {
      this.axios.get('/carts/products/sum').then((res) => {
        // to-do 保存到vuex里面
        this.$store.dispatch('saveCartCount', res)
      })
    }
  }
}

你可能感兴趣的:(vue-cli3)