vuex 使用 (vue2)

在组件中引用

 //1.this.$store.state.xxx
 //2. mapstate
 computed: mapState({
    xxx2: state => state.xxx// 这里引用可以设置 state中 xxx的值 为 xxx2
 })
 // state中多个属性
 computed: {
 	...mapGetters(['xxx']),    // 使用数组的方法直接取值 
    ...mapState(['xxx2']),
    //自定义的 计算属性
    .......
 }
 <template>
 	<div>{{xxx}}<div> <div>{{xxx2}}<div>   // 使用
 </template>
//3.mutations 或者 actions 的方法时  ----   <无参数>
// 同理  调用mutations 或者 actions 的方法时 使用 mapActions, mapMutations

import { mapActions, mapMutations} from 'vuex'
// mapActions例子 ----(mapMutations 一样)
methods: {
    ...mapActions(['increment', 'decrement']),
    // 自定义方法
    name () {}
  }
  // 使用时 可以当 方法直接使用
   <template>
	 	<button @click="increment">+</button>
	    <button @click="decrement">----</button> 
    </template>
// 4.mutations 或 action 的方法有参数时
//mutations 
//1.
this.$store.commit('xxx',name)
//2.
<template>
	 	<button @click="increment">+</button>
</template>
methods: {
    ...mapMutations({
      increment (commit) {   // 点击事件的方法 
        commit('increment', xxx)  // store的方法  xxx是参数
      }
    }),
     // 自定义方法
    name () {}
  }
store 中 的 actions 同理也可以这么写
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Vue2项目中使用Vuex,你可以按照以下步骤进行操作: 1. 检查Vue的版本,确保安装了Vue2.x版本。你可以通过在终端输入`vue -v`命令来查看Vue的版本号。如果你已经安装了Vue2.x版本,可以跳过这一步骤。 2. 如果你之前已经安装过Vue2.x版本,你需要先卸载旧版本的Vuex。你可以使用以下命令: ``` npm uninstall vuex ``` 3. 安装Vuex的最新版本。你可以使用以下命令: ``` npm install vuex@3 ``` 4. 配置Vuex。在你的Vue项目中,你需要在`main.js`文件中引入Vuex并配置它。你可以按照下面的代码示例进行配置: ```javascript import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ // 在这里定义你的state、mutations、actions等 }) new Vue({ store, // ... }).$mount('#app') ``` 在上面的代码中,我们首先导入VueVuex,并使用`Vue.use(Vuex)`来安装Vuex。然后,我们创建了一个新的`Vuex.Store`实例,可以在这里定义你的state、mutations、actions等。最后,我们将`store`实例传递给Vue的根实例中。 这样,你就可以在Vue2项目中成功使用Vuex了。记得根据你的具体需求来定义和使用Vuex的相关内容。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [在Vue2中配置Vuex](https://blog.csdn.net/weixin_44685106/article/details/130447240)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [Vue3+TypeScript + vuex + vue-router 项目创建](https://blog.csdn.net/qq_22841387/article/details/122763893)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值