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

相关推荐
罗超驿15 小时前
5.Java线程创建全攻略:5种写法 + 高频面试题解析
java·开发语言·java-ee
阿拉金alakin20 小时前
UDP 报文结构与核心注意事项总结
网络·网络协议·udp·java-ee
XiYang-DING3 天前
【Java EE】IP协议
网络·tcp/ip·java-ee
XiYang-DING3 天前
【Java EE】IPv6
java·java-ee·php
罗超驿4 天前
1.JavaEE初阶学习安排+介绍计算机是如何工作的
java·学习·java-ee
Bat U5 天前
JavaEE|JVM
java·jvm·java-ee
丑八怪大丑6 天前
会话_过滤器_监听器_Ajax
java-ee
带带弟弟学爬虫__6 天前
dyAPP数据采集-个人主页、发布、搜索、评论
服务器·python·算法·flutter·java-ee·django
辰海Coding6 天前
MiniSpring框架学习-增加事件发布的简化 IoC 容器
java·学习·spring·java-ee
我命由我123456 天前
PHP - PHP 基本随机数生成函数
开发语言·ide·后端·java-ee·php·intellij-idea·intellij idea