vuex+映射

目录

一、vuex作用

二、五个属性方法

 前四种方法用法图示

三、vuex的映射  

1、作用

模块的命名空间 

 2、mapGetters 

(1)没有命名空间

(2)有命名空间

3、mapMutations

(1)没有命名空间

(2)有命名空间

4、mapActions

(1)没有命名空间

(2)有命名空间


一、vuex作用

  • vuex是vue的全局状态的管理工具
  • vuex数据更新,其引用组件都会响应式的更新
  • 如果项目不大,不建议使用vuex

二、五个属性方法

state   

作用:

  • 存放数据的地方
  • vuex中的state数据同渲染指令可以渲染到vue组件中(响应式更新:数据变化视图会自动更新)

组件中使用方法:$store.state.xxx
实例:

// state存储数据的地方
	state: {
		cartNum: 10,
		price: 255,
	},
<p>商品数量 {{$store.state.cartNum}}</p>

getters 

作用:从现有数据计算出新的数据
组件中使用方法:$store.getters.xxx
实例:

// 从现有数据计算出新的数据
	getters: {
		// 价格的百分50%
		// 从现有的价格计算出fee
		fee: function(state) {
			return state.price * 0.5;
		}
	},
<p>商品的提成:{{$store.getters.fee}}</p>

mutations 

作用:mutations是改变vuex state中数据的唯一方式
组件中使用方法:$store.commit(方法,数据)
实例:

// mutations是改变数据state的唯一方式
	// 建议大写
	mutations: {
		// 更改购物车的数量
		SET_CARTNUM(state, data) {
			state.cartNum = data;
		}
	},
<!-- mutations改变cartNum  commit 提交-->
<button @click="$store.commit('SET_CARTNUM',18)"> 改变购物车18</button>

上方简单使用方式只能单个方法对应修改单个数据,下方来拓展延伸下

实现方法的公用性
同一方法修改多个数据
mutations: {
    setAppState(state, [key, value]) {
      state[key] = value;
    },
}
传入不同数据进行修改
this.$store.commit('setAppState', ["flag", true])

其他方法大家可尝试扩展。

 actions  

作用:

  • actions动作,异步,延迟方法,不能直接修改state
  • actions通过 commit 执行 mutations中的方法


组件中使用方法:$store.dispatch(方法,数据)
实例:

// actions动作,异步,延迟方法,不能直接修改state
	actions: {
		setCart(context, data) {
			setTimeout(() => {
				// context就是$store
				// 等待4秒把执行SET_CARTNUM,传参参数data
				context.commit("SET_CARTNUM", data)
			}, 4000)
		}
	},
<button @click="$store.dispatch('setCart',100)">等4秒把购物车数量改为100</button>

 modules 子模块 

介绍:把store分为很多小模块,每一个模块都有自己的state,getters,action,mutation属性,最后合并到一起

使用:新建组件,导入新组件,方法中注册组件

自定义user模块内代码展示

export default {
    state: {
        list: {
            name: "彭于晏"
        }
    },
    mutations: {
        SET_LIST(state, data) {
            state.list.name = data;
        }
    },
}

子模块在组件中使用

  • 注意子模块中数据使用时要在.state后添加模块名
  • 在模块里面访问方法不需要加模块名
<!-- 子模块中数据使用时要在.state后添加模块名 如.user -->

{{$store.state.user.list.name}}

<!-- 在模块里面访问方法不需要加模块名 -->

<button @click="$store.commit('SET_LIST','tky')">单击更改</button>

 前四种方法用法图示

三、vuex的映射  

1、作用

把vuex的数据与方法映射为组件的数据与方法

模块的命名空间 

作用:避免命名冲突     namespaced:true
state的访问默认是有命名空间的
getters,actions,mutations需要开启后才有命名空间

 2、mapGetters 

(1)没有命名空间

...mapGetters({
    fee:"fee"
}),
...mapGetters(["fee"]),

(2)有命名空间

...mapGetters({
    "rank":"test/rank"
})

3、mapMutations

(1)没有命名空间

...mapMutations({
"setUser":"SET_USERINFO"
})

(2)有命名空间

...mapMutaions:{
"setScore":"test/SET_SCORE"
}

4、mapActions

(1)没有命名空间

...mapActions({
    login:"login"
}),
...mapActions(["login"])
}

(2)有命名空间

...mapActions({
    log:"test/login"
})
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个比较复杂的问题,我将尽可能详细地回答你。 首先,你需要在 Vue 项目中安装 Vuex、Vue Router、Element UI 和 Axios 这些库。可以通过以下命令来安装它们: ``` npm install vuex vue-router element-ui axios --save ``` 接下来,你需要创建一个 Vuex 的 store 来存储应用程序的状态。在 store 中,你可以定义一些 mutation、action 和 getter 来改变状态。 在这个示例中,我们需要定义一个 state 来存储我们的数据,例如: ```javascript const state = { items: [], currentItem: {} } ``` 然后,我们需要定义一些 mutation 来改变 state 中的数据。例如: ```javascript const mutations = { setItems(state, items) { state.items = items }, setCurrentItem(state, item) { state.currentItem = item } } ``` 接下来,我们需要定义一些 action 来处理异步请求。例如: ```javascript const actions = { fetchItems({ commit }) { axios.get('/api/items.json').then(response => { commit('setItems', response.data) }) }, addItem({ commit, state }, item) { axios.post('/api/items.json', item).then(response => { commit('setItems', [...state.items, response.data]) }) }, updateItem({ commit, state }, item) { axios.put('/api/items/' + item.id + '.json', item).then(response => { const index = state.items.findIndex(i => i.id === response.data.id) const items = [...state.items] items[index] = response.data commit('setItems', items) commit('setCurrentItem', {}) }) }, deleteItem({ commit, state }, id) { axios.delete('/api/items/' + id + '.json').then(response => { const items = state.items.filter(i => i.id !== id) commit('setItems', items) }) } } ``` 这些 action 将发送请求到我们的 API 并更新 store 中的数据。例如: - `fetchItems` 将获取所有数据并将其设置到 `items` 中。 - `addItem` 将添加一个新的数据项并将其添加到 `items` 中。 - `updateItem` 将更新一个数据项并将其更新到 `items` 中。 - `deleteItem` 将删除一个数据项并将其从 `items` 中删除。 最后,我们需要定义一些 getter 来获取我们的数据。例如: ```javascript const getters = { allItems: state => state.items, currentItem: state => state.currentItem } ``` 现在,我们已经完成了 store 的设置。接下来,我们需要创建一个 Vue 组件来渲染我们的数据,例如: ```html <template> <div> <el-table :data="items" style="width: 100%"> <el-table-column prop="name" label="Name"></el-table-column> <el-table-column prop="age" label="Age"></el-table-column> <el-table-column prop="address" label="Address"></el-table-column> <el-table-column> <template slot-scope="{ row }"> <el-button @click="editItem(row)">Edit</el-button> <el-button @click="deleteItem(row.id)">Delete</el-button> </template> </el-table-column> </el-table> <el-dialog :visible.sync="dialogVisible"> <el-form :model="currentItem" label-position="left" ref="form"> <el-form-item label="Name"> <el-input v-model="currentItem.name"></el-input> </el-form-item> <el-form-item label="Age"> <el-input-number v-model="currentItem.age"></el-input-number> </el-form-item> <el-form-item label="Address"> <el-input v-model="currentItem.address"></el-input> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="dialogVisible = false">Cancel</el-button> <el-button type="primary" @click="submitForm">Save</el-button> </div> </el-dialog> <el-button @click="addItem()">Add Item</el-button> </div> </template> <script> import { mapState, mapActions } from 'vuex' export default { computed: { ...mapState(['items', 'currentItem']) }, methods: { ...mapActions(['fetchItems', 'addItem', 'updateItem', 'deleteItem']), editItem(item) { this.$store.commit('setCurrentItem', item) this.dialogVisible = true }, deleteItem(id) { this.deleteItem(id) }, submitForm() { const form = this.$refs.form form.validate(valid => { if (valid) { if (this.currentItem.id) { this.updateItem(this.currentItem) } else { this.addItem(this.currentItem) } this.dialogVisible = false } }) } } } </script> ``` 在这个组件中,我们使用 Element UI 的表格和表单来渲染我们的数据。我们还使用了 Vuex 的 mapState、mapActions 来将 store 中的状态和操作映射到组件的计算属性和方法中。 现在,我们已经完成了一个基于 Vue、Vuex、Vue Router、Element UI 和 Axios 的增删改查应用程序。当然,这个示例并不是完美的,你可能需要根据你的具体需求做一些适当的调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值