vue+elementUI项目,父组件向子组件传值,子组件向父组件传值,父子组件互相传值。...
时间: 2023-06-21 22:11:34 浏览: 78
1. 父组件向子组件传值:
在父组件中使用子组件时,可以通过在子组件标签中使用属性绑定的方式将数据传递给子组件。例如:
```html
<template>
<div>
<child-component :prop-name="parentData"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentData: '这是来自父组件的数据'
};
}
};
</script>
```
在子组件中,可以通过 `props` 来接收父组件传递过来的数据。例如:
```html
<template>
<div>{{ propName }}</div>
</template>
<script>
export default {
props: {
propName: {
type: String,
required: true
}
}
};
</script>
```
2. 子组件向父组件传值:
在子组件中,可以通过 `$emit` 方法触发自定义事件,并将数据传递给父组件。例如:
```html
<template>
<div>
<button @click="sendDataToParent">向父组件传递数据</button>
</div>
</template>
<script>
export default {
methods: {
sendDataToParent() {
this.$emit('custom-event', '这是来自子组件的数据');
}
}
};
</script>
```
在父组件中,可以通过在子组件标签中监听自定义事件的方式接收子组件传递过来的数据。例如:
```html
<template>
<div>
<child-component @custom-event="receiveDataFromChild"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
receiveDataFromChild(data) {
console.log(data); // 输出:这是来自子组件的数据
}
}
};
</script>
```
3. 父子组件互相传值:
可以将以上两种方式结合起来,实现父子组件互相传值。例如:
```html
<template>
<div>
<child-component :prop-name="parentData" @custom-event="receiveDataFromChild"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentData: '这是来自父组件的数据'
};
},
methods: {
receiveDataFromChild(data) {
console.log(data); // 输出:这是来自子组件的数据
}
}
};
</script>
```
子组件:
```html
<template>
<div>
<button @click="sendDataToParent">向父组件传递数据</button>
</div>
</template>
<script>
export default {
props: {
propName: {
type: String,
required: true
}
},
methods: {
sendDataToParent() {
this.$emit('custom-event', '这是来自子组件的数据');
}
}
};
</script>
```