文章目录
0.vuex复习
2021-11-19 vue笔记-vuex(一) vuex的安装和使用,vuex核心概念:State,Mutation,Action,Getter
1.引入
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
showTabbar:true
},
mutations: {},
actions: {}
})
main.js
import Vue from "vue"
import router from "./router"
import vueRouter from "vue-router"
import App from "./App.vue"
// 引入store下的index.js
import store from './store/index'
import '@/assets/iconfont/iconfont.css'
Vue.use(vueRouter);
Vue.config.productionTip = false;
new Vue({
el: "#app",
router,
store,
render: h => h(App)
})
2.在state中存showTabbar后,直接可以引用
App.vue
<tabbar v-show="this.$store.state.showTabbar"></tabbar>
3.在Detail.vue的两个钩子函数中设置控制showTabbar的布尔值
Detail.vue
beforeMount(){
//console.log("隐藏tabbar...");
// Eventbus.$emit('xianshi',false);
this.$store.state.showTabbar=false;
},
mounted(){
...
},
beforeDestroy(){
//console.log("显示tabbar...");
// Eventbus.$emit('xianshi',true);
this.$store.state.showTabbar=true;
},
4.效果:实现进入详情页时隐藏tabbar
5.为什么要使用mutation?
vuex通过状态管理实现了与非父子通信一样的效果,
因为谁都可以调用和改动,可能会造成滥用,必须进行监管
6.使用mutation监听
6.1.this.$store.commit()的第一个参数就是mutation的名字
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
//自定义共享状态
// showTabbar: true
},
mutations: {
listentabbarShow() {
console.log("修改成显示了...");
},
listentabbarHide() {
console.log("修改成隐藏了...");
},
},
actions: {}
})
Detail.vue
beforeMount(){
console.log("隐藏tabbar...");
// Eventbus.$emit('xianshi',false);
// this.$store.state.showTabbar=false;
this.$store.commit('listentabbarHide',false);
},
mounted(){
...
},
beforeDestroy(){
console.log("显示tabbar...");
// Eventbus.$emit('xianshi',true);
// this.$store.state.showTabbar=true;
this.$store.commit('listentabbarShow',true);
},
6.2.this.$store.commit()的第二个参数就是一个mutation如listentabbarShow(state,data)的第二个参数data
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
//自定义共享状态
showTabbar: true
},
mutations: { //唯一修改状态的位置
listentabbarShow(state, data) {
state.showTabbar = data;
},
listentabbarHide(state, data) {
state.showTabbar = data;
}
},
actions: {}
})
Detail.vue
beforeMount(){
console.log("隐藏tabbar...");
this.$store.commit('listentabbarHide',false);
},
mounted(){
...
},
beforeDestroy(){
console.log("显示tabbar...");
this.$store.commit('listentabbarShow',true);
},