vue组件的一点探索和思考

文章不易,请关注公众号 毛毛虫的小小蜡笔,多多支持,谢谢

来源和问题

在添加主机和修改密码的弹窗中,都有相同的“测试连通及硬件检测”的功能。

如下截图所示:
image.png

目前的实现方式是,分别在两个弹窗中各自写的代码。

那能否抽出来做一个公用的组件呢?

因为测试连通的按钮,点击后执行的代码确实比较多,大概40行。

虽然可以简单抽出来作为mixin,但如果别的页面也要用呢?

想着还是组件复用度和通用性比较高,所以就想抽出来做一个公用组件。

代码如下所示:

// html
<el-form-item>
    <el-button class="test" @click="handleClickTestConnectivity" :disabled="testing" :loading="testing">测试连通及硬件检测</el-button>
    <div v-show="isTestConnectivity" class="tested">
      <img :src="checkSvg" class="xuanze" />
      连接成功!该主机CPU{{ testConnectivityInfo.cores }}核,内存{{ testConnectivityInfo.memory }}G,硬盘{{ testConnectivityInfo.totalSpace }}G
    </div>
    <div v-show="isTestConnectivityFailed" class="testfail">{{ testConnectivityInfo }}</div>
 </el-form-item>
    
// js
handleClickTestConnectivity() {
  const params = {
    hostIp: this.form.hostIp,
    sshPort: this.form.sshPort,
    sshAccount: this.form.sshAccount,
    sshPasswd: this.form.sshPasswd
  }
  this.$refs.form.validate(async (valid) => {
    // 校验通过并且当前没有在测试的任务
    if (valid && !this.testing) {
      this.testing = true
      this.resetCheck()
      try {
        const res = await hostService.testConnectivity(params)
        if (res.code === 0) {
          this.isTestConnectivity = true
          this.testConnectivityInfo = res.data
        }
      } catch (e) {
        if (e.data.code === -1) {
          this.isTestConnectivityFailed = true
          this.testConnectivityInfo = e.data.message
        } else {
          let mes = e.data.message
          if (!mes) {
            mes = '服务器内部错误'
          }
          Notification.error({
            title: '请求失败',
            message: mes,
            position: 'bottom-right'
          })
        }
      } finally {
        this.testing = false
      }
    }
  })
}

分析

问题1

因为需要点击button才发请求,发请求的代码在子组件里面,但参数(form表单)却在父组件那边。

子组件怎么主动从父组件获取到属性数据?


详情 请查看:毛毛虫的小小蜡笔

 

posted @ 2022-05-09 18:14  simonbaker  阅读(26)  评论(0编辑  收藏  举报