美文网首页
组件 组件的传值 父传子

组件 组件的传值 父传子

作者: 雨笑_e29c | 来源:发表于2018-09-24 08:48 被阅读0次

组件是可复用的 Vue 实例,且带有一个名字

<div id="app">

<!-- 可重复使用-->

<my-component></my-component>

<my-component></my-component>

<my-component></my-component>

<my-component></my-component>

<my-component></my-component>

<my-component></my-component>

</div>

<script>

//组件模板中必须有一个根元素(父元素) //全局组件 和Vue同级

Vue.component('my-component',{ template:`

<div>

<h1>嗨</h1> <a href='#'>嘿</a> <h2>哈</h2> <

/div> ` })

new Vue({ el:'#app' })

</script> //局部组件 在Vue实例中

<script>

new Vue({

el: '#app',

data: {

message: 'hello Vue!'

}, //局部组件

components:{ 'my-component':{ template: `

<div>

<p> <a href='#'>百度</a> </p>

</div> `

}

}

})

</script>


在Vue实例中data写法是

new Vue({

el:'#app',

data:{

message:''

      }

})


但是在组件中data必须是一个函数,data中的值还要return]

Vue.component('my-component',{

        data:function(){

            return{

                name:'123'

            }

        }

    })


组件传值(父子间传值) 谁在谁中显示,显示的元素就是父元素,传值用props:['']

<!-- 父子间传值 props:['元素'] 父元素:谁在谁中显示,显示迟来的元素是父元素-->

< div id="app">

<father></father>

</div> Vue.component('father',{ template: `

<div>

<h1>这是父元素</h1>

<child v-bind:number='num'></child>

<button @click='jia'>点击</button> </div> `,

data:function(){

return{

num:1

}

},

methods:{

jia:function(){

this.num++

}

}

})

Vue.component('child',{ props:['number'],

template:

//a标签不能直接获取num的值,显示在父元素中的子元素绑定了子元素中的number元素=num `

<div>

<p>这是子元素</p>

<a href='#'>{{number}}</a>

</div> ` })

new Vue

({

el:'#app'

  })

相关文章