vue 中組件傳值的幾種方法


1. 父組件向子組件傳值

一般會在子組件里面定義props來做接收

父組件:

<template>
  <div>
    <div>我是父組件</div>
      //向子組件傳值msg
    <ChildOne :msg="msg" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "我是父組件,我給你發消息"
    };
  }
};
</script>

子組件

<template>
  <div>
    <div>我接受到的父組件的消息是:{{msg}}</div>
  </div>
</template>

<script>
export default {
    //子組件使用 props 接收傳值
  props: {
    msg: {type: String}
  }
};
</script>

2. 子組件向父組件傳值

這時候就需要利用vue中的$emit將想要傳遞的值通過函數的形式傳出,在父組件接收

this.$emit(arg1,arg2) arg1:方法名字,arg2:要傳出的值

子組件

<template>
  <div>
    <button @click="toParent">向父組件發送信息</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "我是第二組件,我要給父組件傳值"
    };
  },
  methods: {
    toParent() {
        //子組件通過$emit 調用toParent 方法傳遞this.msg值
      this.$emit("toParent", this.msg);
    }
  }
};
</script>

父組件

<template>
  <div>
    <div>我是父組件</div>
	//父組件發現 toParent被調用后 調用getMag方法並接收子組件傳遞過來的值
    <ChildTwo @toParent="getMag" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      child2Msg: ""
    };
  },
  methods: {
    getMag(msg) {
      this.child2Msg = msg;
    }
  }
};
</script>

3. 兄弟組件傳值

這是第一個子組件 -- 從這里向另外一個子組件傳值

<template>
  <div>
    <button @click="toBrother">點我給兄弟傳值</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      toMsg: "哈嘍老二"
    };
  },
  methods: {
    toBrother() {
      this.$emit("sendBrother", this.toMsg);
    }
  }
};
</script>

這是第二個子組件--用來做接收方

<template>
  <div>
    <div>我得到的兄弟組件信息是:{{get}}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      get: ""
    };
  },
  beforeCreate() {
    this.$on("sendBrother", msg => {
      this.get = msg;
    });
  }
};
</script>

4. $parent $children 和$refs

4.1 $refs 父組件可拿到子組件所有的值

//父組件:
<child ref='child'></child>   

//父組件: 
//父組件可以通過 this.$refs. 拿到子組件中的data值和方法
console.log(this.$refs.child.msg)    
this.$refs.child.do()  

4.2 $children 父組件拿到子組件所有的值

$children獲取的是子組件的數組,通過索引找到對應的子組件的實例

//父組件正常 引入 掛載 子組件:
<child></child>     

//父組件:
//父組件可以通過 this.$children[0]. 拿到子組件中的data值和方法
console.log(this.$children[0].msg) this.$children[0].childClick() 

4.3 $parent 子組件獲取所有父組件值

組件通過$parent獲取父組件的數據和方法

//父組件正常 引入 掛載  子組件:
<child></child> 

//子組件:
//子組件中的函數可通過 this.$parent. 拿到父組件中的屬性和方法
childClick() {
      console.log(this.$parent.msg);
      this.$parent.fatherMethod();
    }

注:$root 和 $parent 都能夠實現訪問父組件的屬性和方法,兩者的區別在於,如果存在多級子組件,通過parent 訪問得到的是它最近一級的父組件,通過root 訪問得到的是根父組件(App.vue) 。所以存在組件嵌套的情況下 不要使用 $root 。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM