Vuex使用 1
1、安装 vuex。在控制命令行中输入下边的命令就可以了。
npm n install vuex --save
2、新建store.js文件(可以新建一个文件夹放),文件中引入我们使用的vue和vuex。
import Vue from 'vue';
import Vuex from 'vuex';
//使用vuex,引入之后要Vue.use引用。
Vue.use(Vuex);
现在vuex就算引用成功!!!!!!
*
案例:
(大牛 :技术胖的案例)
先声明一个state的count状态,在页面中使用显示这个count,然后可以利用按钮进行加减
用的是vuex来进行制作,并实现数据的共享。
1.在store.js文件里增加一个常量对象。store.js文件就是在引入vuex时的文件。
const state={
count:1
}
2.还是在store.js 用export default 封装代码,让外部可以引用。
export default new Vuex.Store({
state
})
3.在新建一个vue的模板,位置在components文件夹下,新建vue页面。在模板中我们引入新建的store.js文件,并在模板中用{{$store.state.count}}输出count 的值。
<template>
<div>
<h2>{{msg}}</h2>
<hr/>
<h3>{{$store.state.count}}</h3>
</div>
</template>
<script>
import store from '@/vuex/store'
export default{
data(){
return{
msg:'Hello Vuex',
}
},
store <<-------这里一定要加上
}
</script>
4.在store.js文件中加入两个改变state的方法。
const mutations={
add(state){
state.count++;
},
reduce(state){
state.count--;
}
}
//并在export default 中添加方法
export default new Vuex.Store({
state,
mutations <<------ //这里
})
这里的mutations是固定的写法,意思是改变的,要改变state的数值的方法,必须写在mutations里就可以了。
5.在vue页面模板中加入两个按钮,并调用mutations中的方法。
<div>
<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
</div>