组件:非父子传值

2018-09-21  本文已影响0人  纪美

1.父给子传值 属性 props:['属性']

2.子给父传 用事件传 $emit

3.非父子 用第三方量
例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
 <div class="itany">
   <child></child>
   <child2></child2>
 </div>
<script src="vue.js"></script>
<script>
    var the=new Vue()
   Vue.component('child',{        
        template:`
            <div>
                <p>这是child1</p>
                <button @click="show">传值</button>
            </div>
        `,
       data:function(){
           return{
               mess:'hello Vue'
           }
       },
       methods:{
           show:function(){
               the.$emit('send',this.mess)
           }
       }
        })
   Vue.component('child2',{
       template:`
            <div>
                <p>这是child2</p>
                <a href="#">{{msg}}</a>
            </div>
        `,
       data:function(){
           return{
               msg:''
           }
       },
       mounted:function(){
         the.$on('send',mess=>{
             this.msg=mess;
         }) 
      }
   })
    new Vue({
        el:'.itany'
    })
  </script>
</body>
</html>

注释:点击传值在子组件中传入a标签

上一篇 下一篇

猜你喜欢

热点阅读