JavaEE-Nuxt中的vuex

Nuxt中的vuex

3.1 根模块数据操作

  • 步骤一:创建 store/index.js 添加一个 counter变量,并可以继续累加操作

    js 复制代码
    export const state = () => ({
      counter: 0
    })
    
    export const mutations = {
      increment (state) {
        state.counter++
      }
    }
  • 步骤二:在页面中,使用

    vue 复制代码
    <template>
      <div>
        首页 {{counter}}
        <input type="button" value="+" @click="increment"/>
      </div>
    </template>
    
    <script>
    import { mapState,mapMutations } from 'vuex'
    export default {
      computed: {
        ...mapState(['counter'])
      },
      methods: {
        ...mapMutations(['increment'])
      },
    }
    </script>
    
    <style>
    
    </style>

3.2 其他模块数据操作

  • 步骤一:创建其他模块 store/book.js

    js 复制代码
    export const state = () => ({
      money: 0
    })
    
    export const mutations = {
      addmoney (state) {
        state.money += 5
      }
    }
  • 步骤二:使用指定模块中的数据

    vue 复制代码
    <template>
      <div>
        金额:{{money}} <br>
        <input type="button" value="累加" @click="addMoney(5)">
      </div>
    </template>
    
    <script>
    import {mapState, mapMutations} from 'vuex'
    export default {
      methods: {
        // ...mapMutations({'方法名':'模块/action名称'})
        ...mapMutations({'addMoney':'book/addMoney'})
      },
      computed: {
        //...mapState('模块名称',['变量'])
        ...mapState('book',['money'])
      }
    }
    </script>
    
    <style>
    
    </style>

3.3 完整vuex模板

js 复制代码
// state为一个函数, 注意箭头函数写法
const state = () => ({
  user: 'jack'
})

// mutations为一个对象
const mutations = {
  setUser(state, value) {
    state.counter = value
  }
}
// action执行mutation
const actions = {
  userAction (context,value){
    // 可以发送ajax
    context.commit('setUser',value)
  }

}

// 获取数据
const getters = {
  getUser (state) {
    return state.user
  }
}
export default {
  namespace: true,	// 命名空间,强制要求,在使用时,加上所属的模块名,例如:book/addmoney
  state,
  mutations,
  actions,
  getters
}

3.4. nuxt流程总结

相关推荐
lang201509281 天前
Java JSON绑定API:JSR 367详解
java·java-ee
键盘帽子1 天前
长连接中异步任务的同步等待陷阱:一次主线程阻塞的排查与修复
java·websocket·java-ee·web
木井巳1 天前
【多线程】单例模式
java·单例模式·java-ee
手握风云-1 天前
JavaEE 进阶第十六期:MyBatis,查询请求的生命周期全景图(一)
java·java-ee·mybatis
隐退山林1 天前
JavaEE初阶:文件操作和IO
java·java-ee
lang201509281 天前
Java EE并发工具:JSR 236详解
java·java-ee
dear_bi_MyOnly2 天前
【多线程——线程状态与安全】
java·开发语言·数据结构·后端·中间件·java-ee·intellij-idea
多多*2 天前
2026年最新 测试开发工程师相关 Linux相关知识点
java·开发语言·javascript·算法·spring·java-ee·maven
计算机学姐2 天前
基于SpringBoot的校园流浪动物救助平台
java·spring boot·后端·spring·java-ee·tomcat·intellij-idea
1104.北光c°3 天前
【黑马点评项目笔记 | 登录篇】Redis实现共享Session登录
java·开发语言·数据库·redis·笔记·spring·java-ee