vuex的使用及方法的调用(详解)
1.首先要知道vue中store的index.js的方法:
(1)state :用来存储数据
(2)mutations:用来调用state中的数据
( 3 )actions:异步的步操作操作mutations中传递过来的数据
(4)modules:在state中数据过多时使用,类似于父组件和子组件之间的关系,只不过是需要在 index.js中用import引入调用的定义js文件罢了(如:cart.js)
2.实例的演示
//index.js
import Vue from 'vue'
import Vuex from 'vuex'
import cart from 'cart'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
fenlei:[],//商品分类
list:[]
},
mutations: {
fenleiCart(state,items){
state.fenlei = items
},
LIST(state,item){
state.list = item
}
},
//异步操作
actions: {
fenleiCart(context){
network.detailsfenlei()//该方法是封装axios中的方法
.then(res => {
context.commit("fenleiCart", res.data.data)
console.log(res.data.data);
})
.catch(error => {
console.log(error);
});
}
//若不用封装则可用下面的那个方法
LIST(context){
axios.get("引入的json数据路径").
then(res=>{
context.commit("LIST",res.data)
console.log(res.data)
})
}
},
modules: {
cart
}
})
```javascript
//cart.js
import axios from 'axios'
const cart = {
state: {
},
mutations: {
},
actions: {
},
modules: {
}
}
export default cart
注:该页面的方法与index.js的使用方法相同(不同之处是方法的使用)##
3、在使用页面的调用
<template>
<div class="home">
<div v-for="(item,index) in fenlei" :key="index">
{{item}}
</div>
</div>
</template>
<script>
computed: {
fenlei: function() {
return this.$store.state.fenlei;
//在index.js中的调用方法
return this.$store.cart.state.fenlei;
//在cart.js中的调用方法
}
},
mounted() {
this.$store.dispatch("fenleiCart");
}
</script>
总结:建议方法都在vuex中使用,这样可以在哪里使用就在那里调用,节省了代码量,并且有利于后期的维护。
(不过说实话刚开始就很不习惯,我的建议是多写两遍就好了!哈哈,我了解的就这么多了,欢迎大神的补充和指正。)