vue2.0 仿手机新闻站(三)通过 vuex 进行状态管理

本文详细介绍了如何在Vue项目中引入并使用Vuex进行状态管理,包括创建store结构、在main.js中引入Vuex,以及在App.vue组件中具体使用Vuex的方法。同时,文章还展示了如何利用Vuex的状态管理来控制头部导航栏的显示与隐藏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建 store 结构

 

2.main.js  引入 vuex

 

 

3. App.vue  组件使用 vuex

<template>
  <div id="app">
    <loading v-show="loading"></loading>
    <NavView v-show="headerShow"></NavView>
    <router-view></router-view>
    <FooterView></FooterView>
  </div>
</template>

<script>
/**
 * 引入 组件
 */
// 头部导航
import NavView from './components/Nav.vue'
// 底部选项卡
import FooterView from './components/Footer.vue'

// 引入 vuex 的两个方法
import {mapGetters, mapActions} from 'vuex'

export default {
  // 计算属性
  computed:mapGetters([
    // 从getters中获取headerShow的值
    'headerShow',
    'loading'
  ]),
  watch:{ // 监听,当路由发生变化的时候执行
    $route(to,from){
      if(to.path == '/user-info'){
        /**
         * $store来自Store对象
         * dispatch 向 actions 发起请求
         */
        this.$store.dispatch('hideHeader');
      }else{
        this.$store.dispatch('showHeader');
      }
    }
  },
  components:{
    NavView,
    FooterView
  }
}
</script>

<style lang="scss">
  @import './assets/css/index.css';
</style>

 

4.store

(1)index.js  入口文件

/**
 * 步骤一
 * vuex入口文件
 */
// 引入 vue
import Vue from 'vue'
// 引入 vuex
import Vuex from 'vuex'

import actions from './actions'
import mutations from './mutations'

Vue.use(Vuex);

export default new Vuex.Store({
	modules:{
		mutations
	},
	actions
});

 

(2)type.js  状态(类型)

/**
 * 步骤二
 * types 状态(类型)
 */

 

(3)actions.js  管理事件(行为)

/**
 * 步骤三
 * actions 事件(行为)
 */
// 导出
export default{
	showHeader:({commit}) => {
		// 提交到 mutations
		commit('showHeader');
	},
	hideHeader:({commit}) => {
		// 提交到 mutations
		commit('hideHeader');
	},
	showLoading:({commit}) => {
		commit('showLoading');
	},
	hideLoading:({commit}) => {
		commit('hideLoading');
	}
}

 

(4)mutations.js  突变

/**
 * 步骤四
 * mutations 突变
 */
// 引入 getters
import getters from './getters'

// 定义、初始化数据
const state = {
	header:true,
	loading:false
};

// 定义 mutations
const mutations = {
	// 匹配actions通过commit传过来的值,并改变state上的属性的值
	showHeader(state){
		state.header = true;
	},
	hideHeader(state){
		state.header = false;
	},
	showLoading(state){
		state.loading = true;
	},
	hideLoading(state){
		state.loading = false;
	}
}

// 导出
export default {
	state,
	mutations,
	getters
}

 

(5)getters.js  获取数据

/**
 * 步骤五
 * getters 获取数据
 */
// 导出
export default{
	headerShow:(state) => {
		return state.header;
	},
	loading:(state) => {
		return state.loading;
	}
}

 

.

转载于:https://www.cnblogs.com/crazycode2/p/7576561.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值