vuex修改状态state方法
vuex想要改变state里的属性,官方推荐的方法是通过mutaion的方式修改state。
例如:
store.js
1 2 3 4 5 6 7 8 9 10 11 12 | const state = { num:0 } const mutations = { SET_NUM(state, payload) { state.num= payload; }, } export default new Vuex.Store({ state, mutations }) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | ... export default { data(){ return { num:1 } }, methods:{ doSomething(){ this .$store.commit( 'SET_NUM' , this .num); } } } |
在组件里直接修改state也是生效的,例如:
1 2 3 | doSomething(){ this .$store.state.num = this .num; } |
但是不推荐这种直接修改state的方式,因为这样不能使用vuex的浏览器插件来跟踪状态的变化,不利于调试。
vuex state使用/教程/实例
说明
- 本文用示例介绍Vuex的五大核心之一:state。
官网
state概述
单一状态树
- Vuex 使用单一状态树:用一个对象就包含了全部的应用层级状态。它作为一个“唯一数据源。这也意味着,每个应用将仅仅包含一个 store 实例。
- 单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。
- 存储在 Vuex 中的数据和 Vue 实例中的 data 遵循相同的规则,例如状态对象必须是纯粹 (plain) 的。
响应式
state存放的数据是响应式的:如果store的数据改变,依赖这个数据的组件也会更新。
用法
直接使用
1 2 3 4 5 | // 在JS中使用 this .$store.state.变量名 // 不分模块 this .$store.state.模块名.变量名 // 分模块//在模板上使用 $store.state.变量名 // 不分模块 $store.state.模块名.变量名 // 分模块 |
mapState
1 2 3 4 5 6 7 8 | import { mapState } from 'vuex' export default { computed: { ...mapState([ 'state属性名' ]) // 不分模块,不修改属性名 ...mapState({ '新属性名称' : 'state属性名' }) // 不分模块,修改属性名 ...mapState( '模块名' , [ 'state属性名' ]) // 分模块,不修改属性名 } } |
示例
代码
CouterStore.js
1 2 3 4 5 6 7 8 9 | import Vue from 'vue' ; import Vuex from 'vuex' ;Vue.use(Vuex); const counterStore = new Vuex.Store( { state: { count: 10 }, } ); export default counterStore; |
Parent.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <div class = "outer" > <h3>父组件</h3> </div> import ComponentB from "./ComponentB" ; export default { name: 'Parent' , components: {ComponentB}, } .outer { margin: 20px; border: 2px solid red; padding: 20px; } |
ComponentB.vue(组件)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <div class = "container" > <h3>ComponentB</h3> 计数器的值:{{thisCount}} </div> export default { computed:{ thisCount() { return this .$store.state.count; } } } .container { margin: 20px; border: 2px solid blue; padding: 20px; } |
路由(router/index.js)
1 2 3 4 5 6 7 8 9 10 11 | import Vue from 'vue' import Router from 'vue-router' import Parent from "../components/Parent" ;Vue.use(Router) export default new Router({ routes: [ { path: '/parent' , name: 'Parent' , component: Parent, } ], }) |
测试
访问:http://localhost:8080/#/parent
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。