vue.js2.0父子组件间传参 (一)实现弹窗

来源:互联网 发布:画梁图软件 编辑:程序博客网 时间:2024/05/22 16:47

一。父子传参(父向子传参,子组件不能直接修改参数,另用$emit实现子向父传参)

父:

<template>       <tishi></tishi> <!--子组件--></template>

父向子传:props

父的 html:

<tishi :child="state"></tishi>父的script
 data(){        return{            state:false        }}

修改state,即会影响子接收参数值
  submit(){          this.state = true;}


子 :html
<template>  <div v-if="child">          <button @click="closeBtn">close</button>    </div></template>

子:script 通过props接收

<script>  export default{      data(){          return{ }      },      props:{        child:{              type:Boolean,              default:false          }      },      methods:{        closeBtn(){              console.log(this.child)                      },      }  }</script>

方式:

子组件通过props来接收数据: 
方式1:

props: ['childMsg']
  • 1
  • 1

方式2 :

props: {    childMsg: Array //这样可以指定传入的类型,如果类型不对,会警告}
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

方式3:

props: {    childMsg: {        type: Array,        default: [0,0,0] //这样可以指定默认的值    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这样呢,就实现了父组件向子组件传递数据.


二:子向父传;

那么,如果子组件想要改变数据呢?这在vue中是不允许的,因为vue只允许单向数据传递,这时候我们可以通过触发事件来通知父组件改变数据,从而达到改变子组件数据的目的.

子组件:<template>   
<button @click="closeBtn">close</button></template>methods: {   
closeBtn(){        this.$emit('upDate',false)//主动触发upDate事件,false作为参数传给父组件}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

父组件:

<tishi :child="state" @upDate="change"></tishi>
 //监听子组件触发的upDate事件,然后调用change方法

change(msg){    this.state = msg;}