小言_互联网的博客

Vue 给引入组件初始化传值 《场景:renren-fast-vue向弹出框初始化值》

419人阅读  评论(0)


前提:在使用renren-fast开源项目时,自动生成的项目可以直接生成可用的vue文件,非常好用。但是基本的生成的文件都会将一个实体类拆分成2个文件,即:一个 list 文件、一个 addOrUpdate 文件,而且 addOrUpdate 要依赖list 文件去初始化一些组件的初始值。本篇文章就是针对这个场景进行一个实战说明,也是本人留作回忆记录。

1、生成的文件结构

下图的文件是由renren-fast工具生成的
如果不会使用的朋友可以参考我的这篇文章:Java自动代码生成(逆向工程) [人人开源: renren-generator]

2、问题原因

2.1、list文件:xxx.vue 全部代码

<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-input
          v-model="dataForm.key"
          placeholder="参数名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button
          v-if="isAuth('race:coupon:save')"
          type="primary"
          @click="addOrUpdateHandle()"
          >新增</el-button
        >
        <el-button
          v-if="isAuth('race:coupon:delete')"
          type="danger"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        prop="id"
        header-align="center"
        align="center"
        label="id"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="优惠名称"
      >
      </el-table-column>
      <el-table-column
        prop="type"
        header-align="center"
        align="center"
        label="优惠类别"
      >
        <!--1:针对组别、2:针对赛事】 -->
        <template slot-scope="scope">
          <el-tag :type="scope.row.type == '1' ? 'primary' : 'success'">{
   {
   
            scope.row.type == "1" ? "针对组别" : "针对赛事"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="refId"
        header-align="center"
        align="center"
        label="关联id"
      >
        <!--1:类型为1对应组别id、2:类型为2对应赛事id -->
        <template slot-scope="scope">
          <el-tag :type="scope.row.type == '1' ? 'primary' : 'success'">{
   {
   
            scope.row.type == "1"
              ? "组别id:" + scope.row.refId
              : "赛事id:" + scope.row.refId
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="discount"
        header-align="center"
        align="center"
        label="折扣"
      >
      </el-table-column>
      <el-table-column
        prop="showStatus"
        header-align="center"
        align="center"
        label="是否删除"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == '0' ? 'success' : 'danger'">{
   {
   
            scope.row.status == "0" ? "可用" : "已删除"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="totalCount"
        header-align="center"
        align="center"
        label="该类优惠券总数"
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        label="创建时间"
      >
      </el-table-column>
      <el-table-column
        prop="updateTime"
        header-align="center"
        align="center"
        label="修改时间"
      >
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.id)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
      :raceList = "raceList"
      :raceCategoryList = "raceCategoryList"
    ></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from "./coupon-add-or-update";
export default {
   
  data() {
   
    return {
   
      dataForm: {
   
        key: "",
      },
      raceList:[],// 给子组件传值
      raceCategoryList:[],// 给子组件传值
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
    };
  },
  components: {
   
    AddOrUpdate,
  },
  activated() {
   
    this.getDataList();
    // 获取弹出框的权限下拉
    this.getRaceList();
  },
  methods: {
   
    // 根据登陆token获得该权限下的赛事列表
    getRaceList() {
   
      this.$http({
   
        url: this.$http.adornUrl("/race/info/racelist"),
        method: "get",
      }).then(({
    data }) => {
   
        if (data && data.code === 200) {
   
          this.raceList = data.raceVo;
        }
      });
    },
    // 获取数据列表
    getDataList() {
   
      this.dataListLoading = true;
      this.$http({
   
        url: this.$http.adornUrl("/race/coupon/list"),
        method: "get",
        params: this.$http.adornParams({
   
          page: this.pageIndex,
          limit: this.pageSize,
          key: this.dataForm.key,
        }),
      }).then(({
    data }) => {
   
        if (data && data.code === 0) {
   
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
   
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
   
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
   
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
   
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
   
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
   
        this.$refs.addOrUpdate.init(id);
      });
    },
    // 删除
    deleteHandle(id) {
   
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
   
            return item.id;
          });
      this.$confirm(
        `确定对[id=${
     ids.join(",")}]进行[${
     id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
   
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
   
        this.$http({
   
          url: this.$http.adornUrl("/race/coupon/delete"),
          method: "post",
          data: this.$http.adornData(ids, false),
        }).then(({
    data }) => {
   
          if (data && data.code === 0) {
   
            this.$message({
   
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
   
                this.getDataList();
              },
            });
          } else {
   
            this.$message.error(data.msg);
          }
        });
      });
    },
  },
};
</script>

2.2、addOrUpdate文件:xxxaddOrUpdate.vue 全部代码

<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="优惠名称" prop="name">
      <el-input v-model="dataForm.name" placeholder="优惠名称"></el-input>
    </el-form-item>
    <el-form-item label="优惠类别" prop="type">
        <el-radio-group v-model="dataForm.type">
          <el-radio :label="1">针对组别</el-radio>
          <el-radio :label="2">针对赛事</el-radio>
        </el-radio-group>
      <!-- <el-input v-model="dataForm.type" placeholder="优惠类别【1:针对组别、2:针对赛事】"></el-input> -->
    </el-form-item>
    <el-form-item label="赛事项目">
      <el-select v-model="raceCategorySelected" placeholder="选择赛事项目">
          <el-option
            v-for="item in raceCategoryList"
            :label="item.categoryName"
            :value="item.id"
            :key="item.id"
          >
          </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="关联id" prop="refId">
      <!-- <el-select v-model="raceSelected" placeholder="选择赛事">
          <el-option
            v-for="item in raceList"
            :label="item.raceName"
            :value="item.id"
            :key="item.id"
          >
          </el-option>
      </el-select> -->
      <el-select v-model="raceSelected" placeholder="选择赛事&组别">
          <el-option
            v-for="item in raceList"
            :label="item.raceName"
            :value="item.id"
            :key="item.id"
          >
          </el-option>
      </el-select>
      <!-- <el-input v-model="dataForm.refId" placeholder="关联id【1:类型为1对应组别id、2:类型为2对应赛事id"></el-input> -->
    </el-form-item>
    <el-form-item label="折扣" prop="discount">
      <el-input v-model="dataForm.discount" placeholder="折扣"></el-input>
    </el-form-item>
    <el-form-item label="是否删除" prop="showStatus">
        <el-radio-group v-model="dataForm.showStatus">
          <el-radio :label="1">显示</el-radio>
          <el-radio :label="0">不显示</el-radio>
        </el-radio-group>
      <!-- <el-input v-model="dataForm.showStatus" placeholder="是否【可用】删除【1、可用,2:删除】"></el-input> -->
    </el-form-item>
    <el-form-item label="该类优惠券总数" prop="totalCount">
      <el-input v-model="dataForm.totalCount" placeholder="该类优惠券总数"></el-input>
    </el-form-item>
    <!-- <el-form-item label="创建时间" prop="createTime">
      <el-input v-model="dataForm.createTime" placeholder="创建时间"></el-input>
    </el-form-item>
    <el-form-item label="修改时间" prop="updateTime">
      <el-input v-model="dataForm.updateTime" placeholder="修改时间"></el-input>
    </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
   
    props:[
      "raceList"
    ],
    data () {
   
      return {
   
        visible: false,
        // raceList:[],
        raceSelected: "", // 赛事选中
        // raceCategoryList:[],
        raceCategorySelected:"",//赛事项目选中
        dataForm: {
   
          id: 0,
          name: '',
          type: '',
          refId: '',
          discount: '',
          showStatus: '',
          totalCount: '',
        },
        dataRule: {
   
          name: [
            {
    required: true, message: '优惠名称不能为空', trigger: 'blur' }
          ],
          type: [
            {
    required: true, message: '优惠类别不能为空', trigger: 'blur' }
          ],
          refId: [
            {
    required: true, message: '关联id不能为空', trigger: 'blur' }
          ],
          discount: [
            {
    required: true, message: '折扣不能为空', trigger: 'blur' }
          ],
          showStatus: [
            {
    required: true, message: '是否【可用】删除【1、可用,2:删除】不能为空', trigger: 'blur' }
          ],
          totalCount: [
            {
    required: true, message: '该类优惠券总数不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
   
      init (id) {
   
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
   
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
   
            this.$http({
   
              url: this.$http.adornUrl(`/race/coupon/info/${
     this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({
   data}) => {
   
              if (data && data.code === 200) {
   
                this.dataForm.name = data.coupon.name
                this.dataForm.type = data.coupon.type
                this.dataForm.refId = data.coupon.refId
                this.dataForm.discount = data.coupon.discount
                this.dataForm.showStatus = data.coupon.showStatus
                this.dataForm.totalCount = data.coupon.totalCount
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
   
        this.$refs['dataForm'].validate((valid) => {
   
          if (valid) {
   
            this.$http({
   
              url: this.$http.adornUrl(`/race/coupon/${
     !this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
   
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'type': this.dataForm.type,
                'refId': this.dataForm.refId,
                'discount': this.dataForm.discount,
                'showStatus': this.dataForm.showStatus,
                'totalCount': this.dataForm.totalCount,
              })
            }).then(({
   data}) => {
   
              if (data && data.code === 200) {
   
                this.$message({
   
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
   
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
   
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>

可见由于引入的组件,只有list文件才会有初始化(activated)操作
这里解释一下这个事件

事件 说明
created(): 在创建vue对象时,当html渲染之前就触发;但是注意,全局vue.js不强制刷新或者重启时只创建一次,也就是说,created()只会触发一次;
activated(): 在vue对象存活的情况下,进入当前存在activated()函数的页面时,一进入页面就触发;可用于初始化页面数据等

关键代码:

  activated() {
   
    this.getDataList();
    // 获取弹出框的权限下拉
    this.getRaceList();
  },

3、解决方案

上面全的代码已经可以看到

3.1、 在xxx.vue 初始化

  activated() {
   
    this.getDataList();
    // 获取弹出框的权限下拉
    this.getRaceList();
  },
// 根据登陆token获得该权限下的赛事列表
    getRaceList() {
   
      this.$http({
   
        url: this.$http.adornUrl("/race/info/racelist"),
        method: "get",
      }).then(({
    data }) => {
   
        if (data && data.code === 200) {
   
          this.raceList = data.raceVo;
        }
      });
    },

3.2、 在xxx.vue 给子组件赋值

上一步在success时 this.raceList = data.raceVo; 进行赋值操作
:raceList = “raceList” 给子组件赋值

<!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
      :raceList = "raceList"
      :raceCategoryList = "raceCategoryList"
    ></add-or-update>

3.3、 在 xxxaddOrUpdate.vue 子组件中赋值

首先在 props 中接收传入的参数,必须与上一步 :raceList 保持一致

export default {
   
    props:[
      "raceList"
    ],

3.4、 xxxaddOrUpdate.vue 中给下拉框赋值

raceList 必须与 props中定义的保持一致

	<el-select v-model="raceSelected" placeholder="选择赛事&组别">
          <el-option
            v-for="item in raceList"
            :label="item.raceName"
            :value="item.id"
            :key="item.id"
          >
          </el-option>
      </el-select>

4、成功效果


转载:https://blog.csdn.net/wanglei19891210/article/details/113482113
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场