在uni-app中使用Vuex

悠悠 2021-07-26 19:28 568阅读 0赞

在 uni-app 项目根目录下新建 store 目录,在 store 目录下创建 index.js 定义状态值

  1. const store = new Vuex.Store({
  2. state: {
  3. login: false,
  4. token: '',
  5. avatarUrl: '',
  6. userName: ''
  7. },
  8. mutations: {
  9. login(state, provider) {
  10. console.log(state)
  11. console.log(provider)
  12. state.login = true;
  13. state.token = provider.token;
  14. state.userName = provider.userName;
  15. state.avatarUrl = provider.avatarUrl;
  16. },
  17. logout(state) {
  18. state.login = false;
  19. state.token = '';
  20. state.userName = '';
  21. state.avatarUrl = '';
  22. }
  23. }
  24. })

然后,需要在 main.js 挂载 Vuex

  1. import store from './store'
  2. Vue.prototype.$store = store

最后,在 pages/index/index.vue 使用

  1. <script>
  2. import {
  3. mapState,
  4. mapMutations
  5. } from 'vuex';
  6. export default {
  7. computed: {
  8. ...mapState(['avatarUrl', 'login', 'userName'])
  9. },
  10. methods: {
  11. ...mapMutations(['logout'])
  12. }
  13. }
  14. </script>

发表评论

表情:
评论列表 (有 0 条评论,568人围观)

还没有评论,来说两句吧...

相关阅读