父组件:
<template>
<div class="parent">
<div>我是父组件,给子组件传值(传:我是父组件)----{{msg2}}</div>
<!--在子组件上v-on来监听事件click-msg,一旦触发$.emit('事件名称'),则调用exportMsg方法,这里不要加上括号,写成函数执行的形式-->
<transmit-child :child-msg="msg" @click-msg="exportMsg"></transmit-child>
</div>
</template>
<script>
import child from '@/components/child'
export default {
name: 'parent',
data () {
return {
arr: [1, 2, 3, 4],
msg: '我是父组件',
msg2: ''
}
},
components: {
'transmit-child': child
},
methods: {
exportMsg (childValue) {
console.log('fu')
this.msg2 = childValue
}
}
}
</script>
子组件:
<template>
<div class="child">
<div>我是子组件</div>
<div>{{childMsg}}</div>
<button @click="transmit">通过事件向父组件传递消息</button>
</div>
</template>
<script>
export default {
name: 'child',
data () {
return {
msg: '我是子组件'
}
},
// props是组件的一个单独选项,不能写在data中
props: ['childMsg'],
methods: {
transmit () {
console.log('zi')
// 事件名称('click-msg')和需要传递给父组件的值(msg)
this.$emit('click-msg', this.msg)
}
}
}
</script>
- 父组件传递数据给子组件。是通过子组件设置props选项中自定义属性来接收来自父组件的数据。父组件中子组件的地方使用
v-bind:自定义属性(该属性必须为子组件的props的值)
。父组件传值则为v-bind:自定义属性(该属性必须为子组件的props的值)=‘父组件需要传的值’
。要在子组件中展示父组件传过来的值,就像访问data
属性中的值即可,可以用插值表达式。
另外,props注意点:
1.在js中用驼峰书写
2.在HTML中用连字符书写
3.props属性只读,不可修改。
4.受父组件影响,当父组件相应的数据变化时,子组件属性同样变化。
<div id="app">
this is a parent component
<child-component :parent-msg="msg"></child-component>
</div>
<template id="child">
<div>
<button >click to show</button>
</div>
</template>
<script src="vue.js"></script>
<script>
new Vue({
el:'#app',
data: {
msg: 'this is parent component'
},
components:{
childComponent: {
props:['parentMsg'],
template: '#child'
}
}
})
</script>
- 子组件通过事件触发向父组件传递消息。截取子组件
methods
方法代码如下:
methods: {
transmit () {
console.log('zi')
// 事件名称'click-msg'和需要传递给父组件的值msg,这里可以传多个值,相应的父组件中的方法中,形参要写多个。
this.$emit('click-msg', this.msg, ...)
}
}
点击子组件,执行transmit
方法,进而执行了this.$emit('clickMsg', this.msg)
方法。第一个参数为事件名称,第二个参数为子组件中需要传递给父组件的值。在父组件中子组件的地方使用v-on:clickMsg="exportMsg"
来监听子组件的事件触发。一旦触发,则会执行父组件中的exportMsg
方法,方法代码如下:
methods: {
exportMsg (childValue) {
console.log('fu')
this.msg2 = childValue
}
}
this.$emit('clickMsg', this.msg)
中的this.msg
会传递给childValue
进而达到传值的目的。
下面有注意点,(修改并记于2019.1.16 )
1.不同于组件和 prop,事件名不会被用作一个 JavaScript 变量名或属性名,所以就没有理由使用 camelCase 或 PascalCase 了。并且 v-on 事件监听器在 DOM 模板中会被自动转换为全小写 (因为 HTML 是大小写不敏感的,浏览器会把所有大写字符解释为小写字符),所以 v-on:myEvent
将会变成 v-on:myevent
——导致 myEvent 不可能被监听到。
因此,推荐始终使用 kebab-case 的事件名。
2.第二点谈谈子组件到底是如何触发自定义事件,然后传数据给父组件的?
基于事件绑定,在子组件上用v-on
绑定自定义事件,然后通过某些“行为”,比如,用户点击了子组件,调用了组件中的某个方法,而该方法中调用了vm.$emit()
方法,这便触发了自定义事件,并且在该方法中传递了数据,便传给了父组件。