1.首先要在store/index.js文件配置vuex
vuex基本有state:用来定义共享状态,
actions:实现异步请求操作,
mutations:存放了所有更改状态的方法,
getters : 类似于计算属性,根据vuex的state状态派发一个新的状态出来.
module:
import Vue from 'vue'
import Vuex from 'vuex'
import {instance} from "@/utils/http"//自己封装的ajax请求
Vue.use(Vuex)
let store = new Vuex.Store({
state: { //用来定义共享状态
isTabbarShow:true, //定义tabbar的显示的状态
cinemaList:[] //默认城市影院
},
actions:{ //实现异步请求操作
//异步获取影院相关的数据
getCinemaActions(store){
instance.get("/xxx",{
headers:{
"xxx": "xxx"
}
}).then(res=>{
store.commit("setCinemaList",res.data)
})
}
},
mutations:{ //存放了所有更改状态的方法
show(state){
state.isTabbarShow = true
},
hide(state){
state.isTabbarShow = false
},
setCinemaList(state,data){
state.cinemaList = data
}
},
getters:{
topDataList(state){
return state.cinemaList.splice(0,5)
}
}
})
export default store
2.在页面组件中中触发
触发actions用this.$store.dispatch("getCinemaActions")
触发mutations用this.$store.commit("hide")
触发state用this.$store.state.cinemaList.splice(0,5)
触发getters用$store.getters.topDataList
由于调用比较麻烦,采用辅助函数mapState与mapGetters,mapAction,mapMutations
<1首先组件中引入
import {mapState,mapGetters,mapMutations,mapActions} from "vuex"
computed:{
...mapState(["cinemaList"]),
...mapGetters(["topDataList"]),
},
methods:{
...mapActions(["getCinemaActions"])
...mapMutations(["setCityName"]),
handleClick(item){
//修改vuex的共享状态 城市数据
this.setCityName(item.name)
},
}
使用直接可以调用其方法和函数
<li v-for="data in topDataList"
:key="data.cinemaId">{{data.name}}</li>
computed:{
...
//将输入框的内容与影院的名字进行匹配,如果有的话就会返回数组。
searchDatalist(){
return this.cinemaList.filter(item=>item.name.includes(this.mytext) ||
item.name.toUpperCase().includes(this.mytext.toUpperCase()) ||
item.name.toLowerCase().includes(this.mytext.toLowerCase())
)
}
}
mounted(){
this.getCinemaActions(this.cityId)
},
module拆分
可以将vuex的唯一的store进行module拆分,store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import cinema from "./module/cinemamodule"
import tabbar from "./module/tabbarmodule"
import city from "./module/citymodule"
Vue.use(Vuex)
let store = new Vuex.Store({
modules:{ //进行模块的划分
cinema, //影院的模块
tabbar, //tabbar的模块
city //城市的模块
}
})
export default store
store/module/citymodule.js
const module = {
namespaced: true,//开启命名空间
state:{
cityName:"北京"
},
mutations:{
setCityName(state,name){
state.cityName = name
}
}
}
export default module
使用需要加模块名字
...mapMutations("city",["setCityName"]),
...mapState("city",["cityName"]),
...mapMutations("city", ["setCityName","setCityId"])
...mapState("city", ["cityName","cityId"]),