vuex
导入vuex
- 首先在控制台中输入 npm install vuex
- 在scr目录下创立store目录并且创建store.js来存放数据并修改store.js里的数据
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
//存放数据
state:{
},
//存放对state修改的方法
mutations:{
},
actions:{
//异步操作可以放在这里比如setTimeout
},
getters:{
//对state数据进行加工return值但是不改变state的值
}
})
- 在main.js中引入store
import store from './store/store.js'
//加入store
new Vue({
store,
render: h => h(App),
}).$mount('#app')
这样就可以快乐的使用vuex了
state
state用来存放数据比如以下代码
state:{
count:10
}
这样之后就可以在其他页面中使用啦有以下两种方法调用state的数据
**1.** 直接使用this.$store.state.数据 比如this.$store.state.count
**2.** 也可以在页面按以下代码调用
import {mapState} from './vuex'
<script>
export default{
computed:{
...mapState(['count'])//需要注意引多个state中的值的时候需要...mapState(['count','num'])这样写
}
}
</script>
<html>
<p>{{this.count}}</p>//调用了count值
</html>
mutations
mutations用来书写修改state中的数据中的方法比如下面的代码
//不带参数
mutation:{
Add(state){
state.count--;
}
//带参数
Add2(state,n){
state+=n;
}
}
接下来就可以在页面里进行调用了也有两种方法
**1.**
//app.vue
<script>
export default{
//handle是作为一个点击事件
handle(){
this.$store.commit('add');
}
}
</script>
**2.**
<script>
import mapMutations from 'vuex'
export default{
methods:{
...{mapMutations}(['add']);
handle(){
add2(3);
}
}
}
</script>
actions
actions用来实现异步操作用下面代码声明
//store.js
actions:{
addAsync(context){
setTimeout(() =>{
//写方法
context.commit('add');
},1000)
}
}
接下来也可以愉快地调用了
**1.**
handle(){
this.$store.dispatch('addAsync');
}
**2.**
import {mapActions} from 'vuex'
export default{
methods:{
...mapActions(['addAsync']);
handle(){
addAsync();
}
}
}
getters
用来处理state的数据但是不会改变state的值
如果想改变state的值只能利用mutations的方法
和上面一样先在store.js中声明
getters:{
showState(state){
return '当前的数据是' + state.count;
}
}
接下也和上面一样有两种方法进行调用
*1.*
this.$store.getters.showState
**2.**
import {mapGetters} from 'vuex'
<script>
export default{
computed:{
...mapGetters(['showState'])
}
}
</script>
再将其当作一个数据this.showState来使用就OK了