「Vue」父子组件之间的传值及调用方法

a.父组件向子组件传值
data(){},props数据区别
data中的数据可读可写,是自己的数据
props是个数组,中的数据是父组件传递过来的,只读不能写
<login :dmsg='msg'></login> 父组件向自定义的子组件中传值
var myvue = new Vue({
  el:"#myvue",
  data:{
    flag:'reg',
    msg:'这是父组件'
  },
  methods:{
  },
  components:{
    login:{
      template:'<h2>这是子组件---{{dmsg}}</h2>',
      props:['dmsg'] 子组件定义父组件的传值
      data(){
        return {
          smsg:'这是子组件的自有值'
          }
       }
      }
    }
})
b.子组件调用父组件方法并向父组件传值
<div id="myvue">
  <login :dmsg='msg' @dshow='show'></login> @dshow='show'是父组件方法传递
</div>


<script>
var myvue = new Vue({
  el:"#myvue",
  data:{
    flag:'reg',
    msg:'这是父组件',
    dmsg:null,
  },
  methods:{
    show(data){
    this.dmsg = data
  }
},
  components:{
    login:{
      template:'<div><h2>这是子组件---{{dmsg}}---{{smsg}}</h2><input type="button" name="" id="" value="大按钮" @click="myshow"/></div>',
      props:['dmsg'],
      methods:{
        myshow(){
          this.$emit('dshow',this.smsg) $emit是触发的意思,触发传递过来的方法并传递数据给父方法赋值
    },
},
  data(){
    return {
      smsg:'这是子组件的自有值'
    }
  }
}
}
})
</script>

ref 调用DOM组件和自定义组件,及自定义组件的值和方法,可以实现父组件调用子组件方法
<div id="myvue">
  <h3 ref='myref'>今天天气真好</h3>
  <input type="button" name="" id="" value="获取元素" @click="show"/>
  <login ref='refh2'></login>
</div>


<template id="tmp">
  <h2>今天天气不好</h2>
</template>


var myvue = new Vue({
  el:"#myvue",
  data:{

    },
  methods:{
    show:function(){
      this.$refs.refh2.sshow()
    }
  },
  components:{
    login:{
      template:'#tmp',
      methods:{
      sshow(){console.log('子组件方法')}
    },
  data(){
    return {msg:'哈哈哈'}
}
}
}
})

猜你喜欢

转载自www.cnblogs.com/wrxblog/p/10504446.html