1. 程式人生 > 程式設計 >Vue父子之間值傳遞的例項教程

Vue父子之間值傳遞的例項教程

將通過兩個input框實現父子之間的值傳遞作為演示,效果圖

Vue父子之間值傳遞的例項教程

先註冊父子各一個元件,程式碼如下

<div id="app">
    <parent></parent>
  </div>

  <template id="parent">
    <div>
      <input type="text" v-model="text" placeholder="parent">
      <son></son>
    </div>
  </template>
  <template id="son">
    <div>
      <input type="text" placeholder="son">
    </div>
  </template>
new Vue({
    el: "#app",components: {
      parent: {
        template: '#parent',data() {
          return {
            text: ''
          }
        },components: {
          son: {
            template: '#son'
          }
        }
      }
    }
  })

Vue父子之間值傳遞的例項教程

一、父傳子

再父元件通過屬性傳遞值

 <template id="parent">
    <div>
      <input type="text" v-model="text" placeholder="parent">
      <son :text="text"></son>//通過屬性值傳遞
    </div>
  </template>

子元件通過props屬性接受

 components: {
          son: {
            template: '#son',props:['text'] //通過props屬性接受父傳遞過來的值
          }
        }

這樣我們就可以使用父元件傳遞過來的值了

 <template id="son">
    <div>
      <input type="text" placeholder="son" :value="text">//使用父元素傳遞過來的值
    </div>
  </template>

看下現在的效果

Vue父子之間值傳遞的例項教程

父元件向子元件傳遞成功

二、子傳父

通過父元件自定義事件,然後子元件用$emit(event,aguments)呼叫

<template id="parent">
    <div>
      <input type="text" v-model="text" placeholder="parent">
      <son :text="text" @ev="item"></son>//自定義事件
    </div>
  </template>


components: {
      parent: {
        template: '#parent',components: {
          son: {
            template: '#son',props: ['text']
          }
        },methods: {
          item(v) { //自定義事件觸發的方法
            this.text = v //使用子元件傳遞過來的值改變this.text資料
          }
        }
      }
    }

再子元件觸發自定義事件

<template id="son">
    <div>
      <input type="text" placeholder="son" :value="text" @input="emit" ref="son">//觸發自定義事件
    </div>
  </template>



components: {
      parent: {
        template: '#parent',props: ['text'],methods: {
              emit() {
                this.$emit('ev',this.$refs.son.value) //觸發自定義事件,並傳遞值
              }
            }
          }
        },methods: {
          item(v) {
            this.text = v
          }
        }
      }
    }

這樣就完成了子傳父,父傳子,效果也完成了

總結

到此這篇關於Vue父子之間值傳遞的文章就介紹到這了,更多相關Vue父子值傳遞內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!