vuex的详细使用

本文介绍了Vuex的模块化使用方法,包括引入模块、设置模块、定义状态、getter、mutation和action,以及如何调用模块中的方法。通过将Vuex挂载到原型上,可以在项目全局使用。同时,讲解了如何拆分模块到单独的文件,如goods.js,并在listType.js中定义方法。页面调用时,可以借助mapState等辅助函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以参照vuex官网https://vuex.vuejs.org/zh/guide/

总结:

1.引入模块

  import  {goods} from "./modules/goods"

2.将vuex导入模块

modules:{

   goods

}

3.定义模块

const state={};

const getters={};

const mustations={};

const actions={};

export default {

    namespaced: true,

    state,

    getters,

    mutations,

    actions

}

4.调用方法   

 ...mapState("模块名称",['变量名']

5.变量修改方法文件列表  listType.js

export const SETNUM="setNum"   ;//方法名

//在页面上引入

import {SETNUM} from"../listType.js"

[SETNUM](state,obj){  //@

 state.num+=obj

}


setNumAction({commit,state},obj){

   commit(SETNUM,obj)

}

1)我一般是将vuex挂载到原型上(一般是main.js文件中) ,这样在项目全局都能用

import store from './store'

//将vuex挂载到原型上
Vue.prototype.$store = store

2)在store/index.js中

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    //变量区域
    state: {
        num: 1, //商品数量
        price: 10 //商品价格
    },
    //计算属性
    getters: {
        total: function(state) {
                return state.num * state.price;
            }
            //  total(state){
            //   return state.num * state.price;
            //  }
            // total: state => {
            //     return state.num * state.price;
            // }
    },
    // 方法区域,mutations中才能改变num的值
    mutations: {
        // mutations中方法有两个参数,一个是state,第二个数参数对象[只写一个]
        setNum(state, obj) {
            state.num += obj.n;
        }
    },
    // 异步方法 
    actions: {
        //假设数据n是从接口中拿过来的,假设发送网络请求
        // axios.get().then(res=>{
        //从actions去修改state中的变量
        // })
}
        // setNumAction(store上下文对象,参数对象)
        // etNumAction(context,obj);
        setNumAction({ commit, state }, obj) {
            //去调用mutstion的方法
            commit('setNum', obj)
        }
    },
    //引入模块
    modules: {}
})

3)在页面上调用

<template>
  <div class="home">
    <h1>欢迎使用vuex</h1>
    <h2>商品数量:{{ this.$store.state.num }}</h2>
    <h2>商品价格:{{ this.$store.state.price }}</h2>
    <h2>商品总价:{{ this.$store.getters.total }}</h2>
    <button @click="add">添加功能</button>
  </div>
</template>

<script>
export default {
  name: "Home",
  methods: {
    add() {
      //mustations中定义的方法 用commit来调用
      // this.$store.commit("setNum", { n: 4 });
      //而Actions中定义的方法,用dispatch来调用
      this.$store.dispatch("setNumAction", { n: 4 });
    },
  },
};
</script>

4)还有一种可以借助map的辅助函数 在页面中调用

<template>
  <div class="home">
    <h1>欢迎使用vuex</h1>
    <h2>商品数量:{{ num }}</h2>
    <h2>商品价格:{{ price }}</h2>
    <h2>商品总价:{{ total }}</h2>
    <button @click="add">添加功能</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
  name: "Home",
  data() {
    return {};
  },
  computed: {
    //省略了this.$store.state.变量名的写法
    //通过map函数的解构,将vuex中state变量拿出来,并在当前页面重新生成一个
    ...mapState(["num", "price"]),
    ...mapGetters(["total"]),
  },
  methods: {
    ...mapMutations(["setNum"]),
    ...mapActions([" setNumAction"]),
    add() {
      this.setNum({ n: 5 });
      // this.setNumAction({ n: 3 });
      //mustations中定义的方法 用commit来调用
      // this.$store.commit("setNum", { n: 4 });
      //而Actions中定义的方法,用dispatch来调用
      // this.$store.dispatch("setNumAction", { n: 4 });
    },
  },
};
</script>

(********)此外当然也可以将模块拆分出去  拆分到goods.js中  //用var 或者const都可以

// import {SETNUM} from "../listType.js"  另外一种写法
var state = {
    num: 1, //商品数量
    price: 10, //商品价格

}
var getters = {
    total: function(state) {
        return state.num * state.price;
    }
};
var mutations = {
    // [SETNUM](state,obj){  //另外一种写法
    //     state.num += obj.n;
    // }
    setNum(state, obj) {
        state.num += obj.n;
    }
};
var actions = {
    setNumAction({ commit, state }, obj) {
        //去调用mutstion的方法
        commit('setNum', obj)
    }
};

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}

原来的index.js中,引入goods

import Vue from 'vue'
import Vuex from 'vuex'
//引入
import goods from './modules/goods.js'
Vue.use(Vuex)

export default new Vuex.Store({
    modules: {
        goods
    }
})

 

在listType.js中  [将方法名列表可以单独放到一个文件夹中去]

// export const SETNUM = 'setNum'; //商品数量

由于模块拆分出去了,页面上调用的写法

<template>
  <div class="home">
    <h1>欢迎使用vuex</h1>
    <!-- {{this.$store.state.goods.num}} -->
    <h2>商品数量:{{ num }}</h2>
    <h2>商品价格:{{ price }}</h2>
    <h2>商品总价:{{ total }}</h2>
    <!-- {{this.$store.getters['goods/total']}} -->
    <button @click="add">添加功能</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
  name: "Home",
  data() {
    return {};
  },
  computed: {
    //省略了this.$store.state.变量名的写法
    //通过map函数的解构,将vuex中state变量拿出来,并在当前页面重新生成一个
    //第一个属性名是指定模块的名字
    ...mapState("goods", ["num", "price"]),
    ...mapGetters("goods", ["total"]),
  },
  methods: {
    ...mapMutations("goods", ["setNum"]),
    ...mapActions("goods", [" setNumAction"]),
    add() {
      this.setNum({ n: 5 });
      // this.setNumAction({ n: 3 });
      //mustations中定义的方法 用commit来调用
      // this.$store.commit("setNum", { n: 4 });
      //而Actions中定义的方法,用dispatch来调用
      // this.$store.dispatch("setNumAction", { n: 4 });
    },
  },
};
</script>

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值