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流程总结

相关推荐
我焦虑的编程日记2 天前
【RabbitMQ】RabbitMQ学习
java·数据库·java-ee
阿华的代码王国4 天前
【JavaEE】——线程池大总结
java·开发语言·jvm·java-ee
计算机程序设计开发6 天前
基于Node.js+Express+MySQL+VUE科研成果网站发布查看科研信息科研成果论文下载免费安装部署
数据库·spring boot·mysql·java-ee·课程设计·计算机毕设·计算机毕业设计
计算机专业源码6 天前
基于J2EE技术的高校社团综合服务系统
java·java-ee
阿华的代码王国6 天前
【JavaEE】——多线程常用类和常用数据结构(精华长文)
java·开发语言·java-ee
Yhame.7 天前
Java EE中的编码问题及解决方案
java·java-ee
逸狼7 天前
【JavaEE初阶】文件IO(下)
java·java-ee
matrixlzp8 天前
IDEA 高版本创建 Spring Boot 项目选不到 java 8
java·java-ee·intellij-idea
panjyash9 天前
JAVAEE如何实现网页(jsp)间的数据传输?一文总结
java·java-ee
月临水10 天前
JavaEE: 深入探索TCP网络编程的奇妙世界(四)
网络·tcp/ip·java-ee