Vue.js学习笔记-组件

轩陌

分类: Vue 3458 2

组件概念

组件可以扩展 HTML 元素,封装可重用的代码。
用法:Vue.conponent('tagName', options)
tagName:自定义html标签
options:选项功能代码,data数据必须是一个函数,return返回数据

 

组件之间的通信

   父组件向子组件传递消息使用v-bind:sendDataName="receiveName",子组件接收使用props: ['receiveName']

     sendDataName:父组件发送数据的名字

     receiveName:接收数据的名字

 

   子组件向父组件传递数据使用this.$emit('dataName', arguments),父组件接收使用v-on:dataName="receiveName"

     dataName:子组件向父组件发送数据的名字

     receiveName:methods的一个函数名,函数的arguments为接收的数据

 

实例

   父组件向子组件传递数据


<div id="app">
    <xuan :p-name="parentName"></xuan>
</div>

Vue.component('xuan', {
    template: '
{{ pName }}
', props: ['pName'] }); new Vue({ el: '#app', data: { parentName: '我是父组件的数据' } });

   子组件向父组件传递数据


<div id="app">
    <xuan @children="receive"></xuan>
</div>

Vue.component('xuan', {
    template: '
{{ name }}
', data: function() { return { name: '我是子组件数据' } }, methods: { send: function() { this.$emit('children', this.name) } } }); new Vue({ el: '#app', methods: { receive: function() { console.log(arguments); } } });

   组件与组件的通信


<div id="app">
    <p v-for="(val, key) in children[0]">{{ key }}: {{ val }}</p>
    <xuan :p-name="parentName" @children-send="childrenData"></xuan>
</div>

Vue.component('xuan', {
    template: '
{{ pName }}
', props: ['pName'], data: function() { return { name: '我是子组件数据', summary: '组件之间的通信,点击我可以发送我的数据到父组件' } }, methods: { send: function() { this.$emit('children-send', { name: '子组件数据', summary: '我是来自子组件的数据' }); } } }); Vue.component('mo', { template: '

{{ pSummary }}

', props: ['pSummary'] }); new Vue({ el: '#app', data: { parentName: '我是父组件的数据', children: '' }, methods: { childrenData: function() { this.children = arguments; } } });

未完...

在线展示

  • 12人 Love
  • 2人 Haha
  • 1人 Wow
  • 0人 Sad
  • 0人 Angry
Vue、vue组件

作者简介: 轩陌

打赏

生命的意义在于折腾,一直努力成长中,期待梦想实现的那刻。

共 2 条评论关于 “Vue.js学习笔记-组件”

Loading...