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 天前
音频编辑工具,多端支持基础剪辑易操作
java·网络·windows·java-ee·电脑·maven·excel
手握风云-2 天前
JavaEE 进阶第十期:Spring MVC - Web开发的“交通枢纽”(四)
前端·spring·java-ee
洛_尘2 天前
Java EE进阶4:Spring Web MVC入门
java·java-ee
鸽鸽程序猿3 天前
【JavaEE】【SpringCloud】注册中心_nacos
java·spring cloud·java-ee
田超凡4 天前
深入理解MySQL_6 Temporary临时表
mysql·java-ee
Chan164 天前
【 Java八股文面试 | RabbitMQ篇 】
java·spring boot·spring·面试·java-ee·rabbitmq·java-rabbitmq
码出财富4 天前
SpringBoot 内置的 20 个高效工具类
java·spring boot·spring cloud·java-ee
我命由我123454 天前
充血模型与贫血模型
java·服务器·后端·学习·架构·java-ee·系统架构
符哥20085 天前
学习MySQL之路
mysql·java-ee
手握风云-6 天前
JavaEE 进阶第九期:Spring MVC - Web开发的“交通枢纽”(三)
前端·spring·java-ee