vuex的应用(两个组件间传值、监听vuex值变化)

场景:
需要设计一个页面
左侧为一棵树(接口分组)
右侧为一个列表(接口列表)
点击左侧树种某个节点,右侧列表显示该节点下的接口
树为一个vue、列表为一个vue

上代码
接口分组树vue为 views/appium-tree1/index.vue
接口列表vue为 views/appium-list/index.vue
整个页面vue为 views/appium-list1/index.vue

目录结构:
在这里插入图片描述
组件间值传递用vuex来做
在store\modules下新建appium.js

const state = {
  projId: 1,
  apiGroupId: '',
  apiId: ''
}

const mutations = {
  SET_PROJID: (state, projId) => {
    state.projId = projId
  },
  SET_APIGROUPID: (state, apiGroupId) => {
    state.apiGroupId = apiGroupId
  },
  SET_APIID: (state, apiId) => {
    state.apiId = apiId
  }
}

const actions = {
  changeProjId ({ commit }, data) {
    commit('SET_PROJID', data)
  },
  changeApiGroupId ({ commit }, data) {
    commit('SET_APIGROUPID', data)
  },
  changeApiId ({ commit }, data) {
    commit('SET_APIID', data)
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

getters.js中添加如下内容

  projId: state => state.appium.projId,
  apiGroupId: state => state.appium.apiGroupId,
  apiId: state => state.appium.apiId

如下:
在这里插入图片描述
接下来是要去组件中 取值、赋值、监听数据变化
首先,点击tree中某个节点时,把节点id传给 apiGroupId
el-tree中监听node-click

 @node-click="nodeclick"

如下:
在这里插入图片描述
methods中实现 nodeclick 方法

    nodeclick(node, data, obj) {
      console.log('点击了:', node.id, node.apiGroupName)
      // 这一步是关键,赋值
      this.$store.dispatch('appium/changeApiGroupId', node.id)
      console.log(this.$store.getters.apiGroupId)
    }

然后在接口列表的vue中监听apiGroupId的变化

  watch: {
  	// 方法名是关键
    '$store.getters.apiGroupId'() {
      // 取值
      this.apiGroupId = this.$store.getters.apiGroupId
      console.log('监听到apiGroupId改变', this.apiGroupId)
      // 调method中的方法,调后端接口拿接口数据
      this.getList()
    }
  }

齐活了,接下来是效果图,只有默认分组下有数据
在这里插入图片描述

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值