vue组件传值代码实现
时间: 2024-05-21 19:09:31 浏览: 96
Vue 组件传值有以下几种方式:
1. 父组件向子组件传值:通过 props 属性将数据传递给子组件。
```
//父组件
<template>
<div>
<Child :name="name"></Child>
</div>
</template>
<script>
import Child from "./Child.vue";
export default {
name: "Parent",
components: { Child },
data() {
return {
name: "Tom",
};
},
};
</script>
//子组件
<template>
<div>{{ name }}</div>
</template>
<script>
export default {
name: "Child",
props: {
name: String,
},
};
</script>
```
2. 子组件向父组件传值:通过 emit 方法触发父组件的事件传递数据。
```
//子组件
<template>
<div>
<button @click="sendData">发送数据</button>
</div>
</template>
<script>
export default {
name: "Child",
data() {
return {
message: "Hello World",
};
},
methods: {
sendData() {
this.$emit("send", this.message);
},
},
};
</script>
//父组件
<template>
<div>
<Child @send="getMessage"></Child>
<div>{{ message }}</div>
</div>
</template>
<script>
import Child from "./Child.vue";
export default {
name: "Parent",
components: { Child },
data() {
return {
message: "",
};
},
methods: {
getMessage(data) {
this.message = data;
},
},
};
</script>
```
3. 兄弟组件之间传值:通过一个中央事件总线 bus 实现。
```
//bus.js
import Vue from 'vue';
export const bus = new Vue();
//兄弟组件1
<template>
<div>
<button @click="sendData">发送数据</button>
</div>
</template>
<script>
import { bus } from './bus.js';
export default {
name: "Brother1",
data() {
return {
message: "Hello World",
};
},
methods: {
sendData() {
bus.$emit("send", this.message);
},
},
};
</script>
//兄弟组件2
<template>
<div>{{ message }}</div>
</template>
<script>
import { bus } from './bus.js';
export default {
name: "Brother2",
data() {
return {
message: "",
};
},
created() {
bus.$on("send", (data) => {
this.message = data;
});
},
};
</script>
```
阅读全文