Vuex:数据仓库,解决不同组件数据共享,数据持久化。
数据共享也可以用Localstorage,Sessionstorage实现,大型项目适合用vuex
vuex使用
1.在src目录下新建vuex文件夹 2.在vuex文件夹里面新建一个store.js 3.安装cnpm install vuex --save 4.在store.js中引入以下内容
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
5.定义数据
var state={
count:1
}
6.定义方法,moutations里面的方法主要用于改变state里面的数据
var motations={
inCount(){
++state.count;
}
}
7.暴露对象
const store = new Vuex.Store({
state,
mutations,
})
export default store
8.组建里面使用
a.引入js文件import store from ‘…/vuex/store.js’
b.在export default中注册store
c使用:this.
s
t
o
r
e
.
s
t
a
t
e
.
k
e
y
d
.
改
变
数
据
,
在
方
法
中
写
入
以
下
语
句
,
操
作
m
u
t
a
t
i
n
s
里
面
的
方
法
t
h
i
s
.
store.state.key d.改变数据,在方法中写入以下语句,操作mutatins里面的方法 this.
store.state.keyd.改变数据,在方法中写入以下语句,操作mutatins里面的方法this.store.commit(‘intCount’)