vue 实现父子组件传值和子父组件传值

先上一张图,vue 父子组件传值都用的图片。从张图入手了解如何传参。

一、父组件

1.引入子组件

import random from "./child-random-paper";

2.注册子组件 

components: {
    random,
  },

3. 静态组件,循环体

 <li
        v-for="(item, index) in selectedTypeQuestion"
        :key="item.id"
        :index="index"
        style="margin-top:10px"
      >
//引入子组件
        <random
          :questionType="selectTypeOfQuestion"
          :courseIds="courseId"
          :questionCount="testCountArray[index]"
          :questionTypeIds="questiontypeIdArray[index]"
          :index="index"
          @getValue="getMoreInfo"
          @getSource="getSource"
          @removeRandom="removeRandom"
        ></random>
      </li>

通过循环试题类型数组,渲染子组件 

下拉框内容(每种题型只能出现一次)

4.子组件循环的数组就是这里push的value,是每种渲染出来的题型。

  //下拉框,查看该课程下的题型,如果试题模板为空,则渲染失败,提示输入题型。
    //否则选择子组件
    //查询该课程下的剩余试题
    selectChange(value) {
      //先判断数据中是否有该内容,如果没有加到数据,如果有不加到数组:
      if (this.selectedTypeQuestion.indexOf(value) == -1) {
        if (this.courseTemplate == "" || this.courseTemplate == undefined) {
          this.$confirm("请先输入试卷名称和总分值", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          })
            .then(() => {})
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
        } else {
         this.selectedTypeQuestion.push(value);
    }
}

二、子组件

1.向父组件传值

用$emit函数进行传参,$emit函数用于防止子组件越权。向父组件传参的时候有两个内容,一个是父组件的方法,,这个方法用于监听子组件内容发生变化,及时能传给父组件。另外就是需要传的参数,这里的参数可以是一个,也可以是多个。 

handleChange(value) {
      console.log("题型的总成绩为:" + this.questionTypeAllSource);
      this.AllSource = this.questionTypeAllSource;
      this.$emit(
        "getValue",
        this.formInline,
        this.isExtractModel,
        this.AllSource
      );
    },

2.传递过去的参数(对象的形式),每个变量在父页面显示,动态变化

 formInline: {
        // 题型名称
        questionType: "",
        // 题型个数
        questionNum: "0",
        // 每题分数
        questionValue: "0",
        // 该题型的总共的分数
        AllSource: "",
        optionDisorder: "",
        //是否按空给分
        isBlanks: 0,
        //试题分类id
        questionClassifyId: "随机",
        // 章节id  
        questionClassifyObject: "",
        //是否自定义
        isCustom: 0,
        degree: 0,
        //是否必抽题
        isExtracts: 0,
        //当前剩余可选数量
        currentNum: "",
      },

 对应关系

3.接受父组件传过来的值(用props接受) 

// 接受父组件传递过来的题型
  props: {
    questionType: {
      type: String,
      default: "",
    },
    index: "",
    questionLists: "",
    //每次循环渲染的时候传进来的题库剩余个数
    questionCount: "",
    //每次循环渲染的时候传进来的题型Id
    questionTypeIds: "",
    //课程id
    courseIds: "",
  },

 运用,下拉框为父组件的内容,选中的时候传到子组件,显示出来。

三、效果

猜你喜欢

转载自blog.csdn.net/yyp0304Devin/article/details/106882845