uniapp的vue2兄弟之间传值
时间: 2023-07-18 11:07:01 浏览: 44
在 Vue2 中,组件之间可以通过 props 和 $emit 进行传值。
1. 父组件向子组件传值
父组件可以通过 props 向子组件传值,子组件通过接收 props 来获取传递过来的值。
```html
<!-- 父组件 -->
<template>
<div>
<child-component :msg="parentMsg"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent'
export default {
components: {
ChildComponent
},
data() {
return {
parentMsg: 'Hello world!'
}
}
}
</script>
```
```html
<!-- 子组件 -->
<template>
<div>
<p>{{ msg }}</p>
</div>
</template>
<script>
export default {
props: {
msg: {
type: String,
default: ''
}
}
}
</script>
```
2. 子组件向父组件传值
子组件可以通过 $emit 向父组件传值,父组件通过监听子组件的事件来获取传递过来的值。
```html
<!-- 子组件 -->
<template>
<div>
<button @click="handleClick">点击传递数据到父组件</button>
</div>
</template>
<script>
export default {
methods: {
handleClick() {
this.$emit('child-msg', 'Hello world!')
}
}
}
</script>
```
```html
<!-- 父组件 -->
<template>
<div>
<child-component @child-msg="getChildMsg"></child-component>
<p>从子组件传递过来的数据:{{ childMsg }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent'
export default {
components: {
ChildComponent
},
data() {
return {
childMsg: ''
}
},
methods: {
getChildMsg(msg) {
this.childMsg = msg
}
}
}
</script>
```