vue技巧

vue的父子传值方法:
子传父:

子组件使用this.$emit("自定义事件名",需要传的数据)
父组件使用 @自定义事件名="自定义的方法名"

例如:

//子组件
<template>
  <div>
    <button @click="topro">子传父</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      msg: "子组件数据",
    };
  },
  methods: {
    topro() {
      this.$emit("toParent", this.msg);
    },
  },
};
</script>
//父组件
<template>
  <div class="hello">
    <Child @toParent="promet"></Child>
  </div>
</template>
<script>
import Child from "@/components/child.vue";
export default {
  name: "HelloWorld",
  components: {
    Child,
  },
  methods: {
    promet() {
      console.log(this.$refs.Child.msg);
    },
  }
};
</script>

父传子:

在父组件中使用 :自定义数据名="需要传的数据"
在子组件中使用props来接收
方法一:
props:{
      自定义数据名:数据类型
 }
props:{
      msg:Number
}
方法二:
props:['自定义数据名']
props:['msg']

例如:

//父组件
<template>
  <div class="hello">
    <Child :msg="123" ></Child>
  </div>
</template>
<script>
import Child from "@/components/child.vue";
export default {
  name: "HelloWorld",
  components: {
    Child,
  }
};
</script>
//子组件
<template>
  <div>
    <p>{{ msg }}</p>
  </div>
</template>
<script>
export default {
  data() {
    return {
    };
  },
  props: {
    msg: Number,
  },
};
</script>

父组件调用子组件的方法:

//在子组件中定义一个方法
<script>
export default {
methods: {
    ale() {
      alert("111111111111");
    }
  },
};
</script>
//父组件
<template>
  <div class="hello">
    <Child ref="Child"></Child>
    <button @click="tap">调用子组件方法</button>
  </div>
</template>
<script>
import Child from "@/components/child.vue";
export default {
  name: "HelloWorld",
  components: {
    Child,
  },
  methods: {
    tap() {
      this.$refs.Child.ale();
    },
  },
};
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容