vuex使用方法

本文详细介绍了如何使用Vuex在Vue项目中进行状态管理,包括创建store、定义state、getters、actions和mutations,以及组件中如何通过Vuex进行数据交互。通过实例展示了如何在组件间传递和更新状态。
摘要由CSDN通过智能技术生成

第一种使用方法(还有不同的方法下次整合进来,不过原理都是一样,)

1. 在项目中建 store 文件夹文件夹下建如图所示文件。

2.在index.js 中定义默认值 并将其他文件中的方法引入且注册到 vuex.Store 中

	
import Vue from 'vue'
import Vuex from 'vuex'
import * as getters from './getters' 
import * as actions from './actions'
import * as mutations from './mutations'
 
Vue.use(Vuex)
const state = {
    idiomName: '夕阳西下' // 默认值
}
 
const store = new Vuex.Store({
    state,    // 共同维护的一个状态,state里面可以是很多个全局状态
    getters,  // 获取数据并渲染
    actions,  // 数据的异步操作
    mutations  // 处理数据的唯一途径,state的改变或赋值只能在这里
})
 
export default store  // 导出store并在 main.js中引用注册。

3. action.js 注册事件处理函数,当这个函数被触发时,将状态提交到mutations中处理。

// commit 提交;name即为点击后传递过来的参数,(点击事件触发)
export const actionChangeName = ({commit}, name) => commit ('mutationsChangeName', name)

4.multations.js 提交 mutations是更改vueX状态的唯一合法方法。

export const mutationsChangeName = (state, name) => { // 由action 中的提交触发
  console.log(state,name)
  state.idiomName = name // 把方法传递过来的参数,
}

5. getters.js vuex状态管理的第一站也是最后一站,获取数据并渲染。

// 获取最终的状态信息 
export const idiomName = state => state.idiomName

6. 最后把组件代码贴上

<template>
  <div class="app-container">
    <h1>待修改成语名称:{{idiomName}}</h1>
    <el-button type="primary" @click="changeName('飞扬跋扈')">修改为 飞扬跋扈</el-button>
    <el-button type="primary" @click="changeName('貌美如花')">修改为 貌美如花</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  created() {},
  methods: {
    changeName(name){
      this.$store.dispatch('actionChangeName',name); // 触发actions中的方法并传递参数
    },
  },
  computed: {
      idiomName(){
        return this.$store.getters.idiomName; // 更新idiomName 的状态
      }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  h1{
    padding: 20px;
    color: #999;
  }
  .el-button{
    margin-top: 20px;
  }
}
</style>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值