Vue父子組件傳值的方法


1.父向子傳值props

父組件:<child :inputName="name">

子組件:

(1)props: {
   inputName: String,

   required: true

  }

(2)props: ["inputName"]


2.子組件向父組件傳值$emit

子組件:

 <span>{{childValue}}</span>

 <!-- 定義一個子組件傳值的方法 -->

  <input type="button" value="點擊觸發" @click="childClick">


 export default {
  data () {
   return {
    childValue: '我是子組件的數據'

   }

  },

  methods: {
   childClick () {  

    this.$emit('childByValue', this.childValue)

   }

  }

 }


父組件

<!-- 引入子組件 定義一個on的方法監聽子組件的狀態-->

<child v-on:childByValue="childByValue"></child>

methods: {
   childByValue: function (childValue) {
    // childValue就是子組件傳過來的值

    this.name = childValue

   }

  }

}


3.父組件調用子組件的方法通過ref

在DOM元素上使用$refs可以迅速進行dom定位,類似於$("selectId")

使用this.$refs.paramsName能更快的獲取操作子組件屬性值或函數

子組件:

methods:{
childMethods() {
        alert("I am child's methods")

}

}


父組件: 在子組件中加上ref即可通過this.$refs.method調用

<template>

  <div @click="parentMethod">

    <children ref="c1"></children>

  </div>

</template>


<script>

  import children from 'components/children/children.vue'

  export default {
    data(){
      return {
      }

    },

    computed: {
    },

    components: {      

      'children': children

    },

    methods:{
      parentMethod() {
        console.log(this.$refs.c1) //返回的是一個vue對象,可以看到所有添加ref屬性的元素

        this.$refs.c1.childMethods();

      }

    },

    created(){
    }

  }

</script>

4.可以通過$parent和$children獲取父子組件的參數


我們可以使用$children[i].paramsName 來獲取某個子組件的屬性值或函數,$children返回的是一個子組件數組


那么子組件怎么獲取修改父組件的數據內容?這需要使用$parent



5.vue 全局事件(eventBus)

在main.js里:window.eventBus = new Vue();//注冊全局事件對象


在文件列表里 <span >{{ item }}<button @click="down(item)">下載</button></span>


另一組件的監聽

6.兄弟之間的傳值Vuex

在state里定義數據和屬性

在 mutations里定義函數fn,在頁面通過

this.$store.commit('fn',params)來觸發函數,Vuex在這里不做詳細介紹了


免責聲明!

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



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