您的位置:首页 > 产品设计 > UI/UE

状态管理工具vuex初识

2017-09-13 10:21 706 查看
首先安装vuex:npm install vuex --save然后在index.html同级新建文件夹store,在文件夹内新建index.js文件,这个文件我们用来组装模块并导出 store 的文件
【一、获取store中的数据】
import Vue from 'vue'
import Vuex from 'vuex'

// 告诉 vue “使用” vuex
Vue.use(Vuex)

// 创建一个对象来保存应用启动时的初始状态
// 需要维护的状态
const store = new Vuex.Store({
state: {
// 放置初始状态 app启动的时候的全局的初始值
bankInf: {"name":"我是vuex的第一个数据","id":100,"bankName":"中国银行"}
}
})
// 整合初始状态和变更函数,我们就得到了我们所需的 store
// 至此,这个 store 就可以连接到我们的应用中
export default store
在main.js文件中注册store
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './../store/index'

/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})任意组件中使用store中的数据,就是使用计算属性返回store中的数据到一个新属性上
<div class="bank">
<list-header :headerData="bankName"></list-header>
04银行详情页面
<input name="" v-model="textValue">
<button type="button" name="获取数据" @click="newBankName"></button>
</div>【二、在组件中修改store中的状态
】 
this.$store.commit

export default {
...
computed: {
bankName() {
return this.$store.state.bankInf.bankName;
}
},
methods: {
newBankName: function() {
this.$store.commit('newBankName', this.textValue)
}
}
...
}
在store中的index.js中添加mutations:
const store = new Vuex.Store({
state: {
// 放置初始状态 app启动的时候的全局的初始值
bankInf: {"name":"我是vuex的第一个数据","id":100,"bankName":"中国银行"},
count:0
},
mutations: {
newBankName(state,msg) {
state.bankInf.bankName = msg;
}
}
})

如果在使用中发现报错this.$store.commit is not a function ,请打开你项目的配置文件package.json,查看你正在使用的vuex的版本,我正在使用的是vuex2.0,

如果想删除旧版本的vuex并安装新版本的vuex请使用

npm rm vuex --save

然后安装最新的vuex

npm install vuex --save

即可解决这个错误,或者是查看vuex官网api修改提交mutation的语句

原文出自:http://www.cnblogs.com/jasonwang2y60/p/6433082.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: