vue 父子组件传值

6,951 阅读1分钟
在Vue中,父子组件的关系可以总结为prop向下传递,事件向上传递。父组件通过prop给子组件下发数据,子组件通过事件给父组件发送信息。


父组件向子组件传值:

父组件:

  data() {
    return {
      fatherData: 'I am the father'
    }
  },
在html中将father传给子组件:
 <child :father="fatherData"></child>

子组件:

接收父组件的数据---props
  props:{
       father: {
          type: String,
          required: true,   // 必填数据
          default:100,   //带有默认值的数据
    },
  },
现在即可使用父组件的数据,但不能修改父组件的值,若要变化,可在子组件中重新赋值使用。

子组件修改父组件的数据 .sync

父组件:
 <child :father.sync="fatherData"></child>
子组件:
 this.$emit('update:father', 'zaijian')

父组件向子组件传方法:

父组件:
    giveMethods(){
      console.log('方法传给子组件')
    }
    <child @giveMethod="giveMethods"></child>子组件:
      this.$emit('giveMethod')即可调用这个方法

子组件向父组件传值(通过事件传值):

在子组件定义一个通过传值的事件:
  <div @click="sendData" class="child">我是子组件</div>
  data() {
    return {      child: 'I am the child'    }  },
    sendData() {      this.$emit('sendChild', this.child)    }

父组件:

    <child @sendChild="giveChilds"></child>
    //  传入的参数data即为传入的值
    giveChilds(data) {      console.log(data)    }

子组件向父组件传方法(通过事件):

子组件传方法的事件:(可带参数)
<div @click="prizeStatus(receive, id)"></div>
js:
prizeStatus(receive, id) {
    this.$emit("sendIndex", status, id);
}

父组件接收:
<award @sendIndex="showPrize"></award>js:
showPrize(index, id){
    console.log('get method')
}

vue动态修改引用类型值:$set

vm.$set(vm.items, indexOfItem, newValue)
如:   that.$set(that.getWord, 0, 1)