vue 组件间传值的几种方式

一、子组件更改父组件数据

(1)props传递方法

通过props的方式,将父组件的方法传递到子组件,在子组件中通过props接收,可以在当前组件的实例上直接触发父组件的方法,从而实现子组件更改父组件的值。同事也可以将子组件的数据,以参数的形式发送给父组件。

<!--
父组件,设置更改自己数据的方法,将该方法传递给子组件
-->
<template>
  <div class="home">
    <h1>我是父组件</h1>
    <HelloWorld :msg="msg" :changeMsg="changeMsg"/>
  </div>
</template>
 
<script>
import HelloWorld from '@/components/HelloWorld.vue'
 
export default {
  name: 'Home',
  components: {
    HelloWorld
  },
  methods:{
    changeMsg(text,num){
      console.log(text,num);
      this.msg=this.msg+1
    }
  },
  data(){
    return{
      msg:1
    }
  }
}
</script>

<!-- 
子组件,接收父组件传递过来的方法,通过props接收到的方法和数据,在组件实例上可以直接获取和触发 
-->
<template>
  <div class="hello">
    <h1>我是子组件<button @click="changeFatherData">点我更改父组件数据</button></h1>
    <h1>父组件数据:{{msg}}</h1>
    
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: Number,
    changeMsg:Function
  },
  data(){
    return{
      text:"我是子组件数据,我要发送给父组件",
      num:12
    }
  },
  methods:{
    changeFatherData(){
      this.changeMsg(this.text,this.num)
    }
  },
}
</script>
 
<style scoped lang="scss">
 
</style>
 

(2)通过this.$emit触发父组件方法实现

在父组件中自定义一个方法,然后传递给子组件,子组件通过this.$emit直接触发父组件中的数据,实现父子组件通信。子组件触发事件,父组件监听事件。

<!--
父组件,将定义的方法传递给子元素
-->
<template>
  <div class="home">
    <h1>我是父组件</h1>
    <HelloWorld :msg="msg" @changeMsg="changeMsg"/>
  </div>
</template>
 
<script>
import HelloWorld from '@/components/HelloWorld.vue'
 
export default {
  name: 'Home',
  components: {
    HelloWorld
  },
  methods:{
    changeMsg(text,num){
      console.log(text,num);
      this.msg=this.msg+1
    }
  },
  data(){
    return{
      msg:1
    }
  }
}
</script>
 
 
<!--
子组件,通过this.$emit触发父组件方法,更改父组件数据,同时可以进行数据传值
-->
<template>
  <div class="hello">
    <h1>我是子组件<button @click="changeFatherData">点我更改父组件数据</button></h1>
    <h1>父组件数据:{{msg}}</h1>
  </div>
</template>
<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: Number,
  },
  data(){
    return{
      text:"我是子组件数据,我要发送给父组件",
      num:12
    }
  },
  methods:{
    changeFatherData(){
      this.$emit('changeMsg',this.text,this.num)
    }
  },
}
</script>
<style scoped lang="scss">
</style>

二、父组件修改子组件的值

(1)可以通过ref的方式调用子组件的方法改变子组件的值

props只支持第一次加载这个组件的时候获取父组件的值,后续修改父组件的值得时候子组件并不会动态的更改。

可以通过ref的方式调用子组件的方法改变子组件的值。

<!--
子组件
-->

<template>
  <div>
    <span>{{data}}</span>
  </div>
</template>
<script>
export default {
  data() {
    return {
        data:'就要被修改啦'
    };
  },
  methods: {
    a(val) {
        this.data=val;
    },
  },
};
</script>

<!--
父组件
-->

<template>
  <div>
    <child ref='child'></child>
  </div>
</template>
<script>
export default {
  mounted(){
  	setTimeout(()=>{
  		this.$refs.child.a("把你修改了");
  	},3000)
  }
  components:{
  	child:()=>import("../components/child.vue")
  }
};
</script>

posted @ 2022-08-03 11:05  littlewrong  阅读(539)  评论(0编辑  收藏  举报