第一步:下载vuex
cnpm install vuex -S
第二步:创建store文件夹,文件夹下创建index.js文件,配置文件
// 引入Vue
import vue from 'Vue'
// 引入Vuex
import vuex from 'Vuex'
// 使用vuex
vue.use(vuex)
// 创建仓库
let vuex = new vuex.Store({
// 全局数据
state : {
},
// 改变数据
mutations:{
}
})
第三步:main入口文件,引入index.js
import store from './store/index'
store挂载到vue实例
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>',
store
})
第四步:
App组件中访问定义的对象
console.log(this.$store.state.count)
count定义的对象
如图所示:
![48ec0c6fbd0261b3e3fb5ac5467ffca8.png](https://img-blog.csdnimg.cn/img_convert/48ec0c6fbd0261b3e3fb5ac5467ffca8.png)
第五步:
App组件通过计算属性访问对象数据
computed: {
count(){
return this.$store.state.count
}
},
第六步:
页面使用定义的属性
数量:{{ this.$store.state.count }}
想修改数据就在store文件夹下的index.js文件中的
// 改变数据
mutations:{
add(state){
state.count++
}
}
页面使用变量,如图所示:
![fe1695870f9db7c781a5d077537cb55d.png](https://img-blog.csdnimg.cn/img_convert/fe1695870f9db7c781a5d077537cb55d.png)
第七步:
然后在APP组件中定义方法add
<button @click="add">+</button>
第八步在APP组件中的methods中定义方法
methods: {
add(){
this.$store.commit('add')
}
},
想点击减号改变数据和点击加号一样的方法
在store文件夹下的index.js文件中的
// 改变数据
mutations:{
add(state){
state.count--
}
}
然后在APP组件中定义方法jian
<button @click="jian">-</button>
第八步在APP组件中的methods中定义方法
methods: {
jian(){
this.$store.commit('jian')
}
},
有按钮后的页面效果,可以点击增加减小如图所示:
![1ac0945d53343d5b1dc0bf6bac7b604d.png](https://img-blog.csdnimg.cn/img_convert/1ac0945d53343d5b1dc0bf6bac7b604d.png)
这就是一个页面使用vuex的实现数据改变的效果