vue组件传值

我心飞翔 分类:vue

父传子

通过组件的props,直接自上而下直接传给子组件

1//父组件
2<template>
3  <div><sonCom :users="users"></sonCom></div>
4</template>
5
6<script>
7import sonCom from "./Son.vue";
8export default {
9  name: "fatherCom",
10  data() {
11    return {
12      users: ["Henry", "Bucky", "Emily"],
13    };
14  },
15  components: {
16    sonCom,
17  },
18};
19</script>
1//子组件
2<template>
3  <div>
4    <ul>
5      <li v-for="i in users" :key="i">{{ i }}</li>
6    </ul>
7  </div>
8</template>
9
10<script>
11export default {
12  name: "sonCom",
13  props: {
14    users: {
15      //这个就是父组件中子标签自定义名字
16      type: Array,
17      required: true,
18    },
19  }
20};
21</script>

子传父

通过子组件的自定义事件传递。

this.$emit向父组件暴露一个监听事件,第一个参数为事件名称,第二个参数为传递的值

1//子组件
2<template>
3  <div>
4    <button @click="onEmit">点我给父组件传值</button>
5  </div>
6</template>
7
8<script>
9export default {
10  name: "sonCom",
11  methods: {
12    onEmit() {
13      this.$emit("onFatherGetSon", "子向父组件传值");
14    },
15  },
16};
17</script>
1<template>
2  <div>
3    <sonCom @onFatherGetSon="updateStr"></sonCom>
4    <div>子传父:{{ fatherGetSonStr }}</div>
5  </div>
6</template>
7
8<script>
9import sonCom from "./Son.vue";
10export default {
11  name: "fatherCom",
12  data() {
13    return {
14      fatherGetSonStr: "",
15    };
16  },
17  components: {
18    sonCom,
19  },
20  methods: {
21    updateStr(e) {
22      //监听事件,第一个参数为传过来的值
23      this.fatherGetSonStr = e;
24    },
25  },
26};
27</script>

兄弟组件传值

1.创建一个新的vue实例,用来当事件中心。通过vue实例的$emit,$on方法,可以实现任意传递

2.通过vuex

回复

我来回复
  • 暂无回复内容