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

相关推荐
弹简特1 天前
【JavaEE】MyBatis-Plus 条件构造器速查表
java-ee·mybatis
二进制person1 天前
JavaEE进阶 --Spring Framework、Spring Boot和Spring Web MVC(2)
spring boot·spring·java-ee
competes2 天前
深圳程序员职业生涯
java·大数据·开发语言·人工智能·java-ee
Boop_wu2 天前
[Java EE 进阶] Spring Boot 日志全面解析 : 配置与实战
junit·java-ee·单元测试
competes2 天前
学生需求 交易累计积分,积分兑换奖品
java·大数据·开发语言·人工智能·java-ee
我命由我123452 天前
Android Gradle - Gradle 自定义插件(Build Script 自定义插件、buildSrc 自定义插件、独立项目自定义插件)
android·java·java-ee·kotlin·android studio·android-studio·android runtime
堕2743 天前
JavaEE初阶——《多线程--. 多线程带来的的⻛险-线程安全 (重点)》
java·算法·java-ee
杭州杭州杭州3 天前
J2EE实验
java·java-ee
弹简特4 天前
【JavaEE】Mybatis实现分页查询功能
java·java-ee·mybatis