vue2.0 父子组件传值
时间: 2023-05-10 17:01:27 浏览: 144
Vue 2.0 中父子组件之间的传值可以通过属性(prop)和事件(event)实现。
1. 属性(prop)传递值
父组件通过在子组件上定义prop属性,指定要传递的值类型和名字,然后将值传递给子组件的prop属性。子组件通过props接收到父组件传递的值,可以直接使用。
例如:父组件中定义一个名为message的prop属性,值为字符串类型,在模板中通过子组件标签向子组件传递值。
```
// 父组件
<template>
<div>
<child-component :message="hello"></child-component>
</div>
</template>
<script>
import ChildComponent from './child-component.vue'
export default {
components: { ChildComponent },
data () {
return {
hello: 'hello, world'
}
}
}
</script>
// 子组件
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
props: {
message: {
type: String,
require: true
}
}
}
</script>
```
2. 事件(event)传递值
父组件通过定义一个事件,在子组件中触发该事件并传递需要传递的值。子组件在父组件中使用子组件自定义的事件,并获取到传递的值。
例如:子组件定义一个自定义事件,触发时传递一个字符串类型的值。父组件中使用子组件,同时监听子组件的自定义事件,在事件回调函数中获取到子组件传递的值。
```
// 子组件
<template>
<button @click="changeMessage()">改变消息</button>
</template>
<script>
export default {
methods: {
changeMessage () {
this.$emit('change', '新消息')
}
}
}
</script>
// 父组件
<template>
<div>
<child-component @change="handleChange"></child-component>
<div>{{ message }}</div>
</div>
</template>
<script>
import ChildComponent from './child-component.vue'
export default {
components: { ChildComponent },
data () {
return {
message: '旧消息'
}
},
methods: {
handleChange (newValue) {
this.message = newValue
}
}
}
</script>
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)