1. 程式人生 > >vue2.0父子元件雙向繫結

vue2.0父子元件雙向繫結

父元件程式碼如下。這裡要注意的有:
1. 父組建使用msg向子元件傳遞資料。
2. 子附件向父附件傳送xxx訊息,父元件收到訊息後用abc方法來處理。

<template>
  <div>
    <input type="text" v-model="msg">
    <br>
    <child :inputValue="msg" v-on:xxx="abc"></child>
  </div>
</template>
<style></style>
<script
>
import child from './childCom.vue' export default{ data(){ return { msg: '請輸入' } }, components: { child }, methods: { abc: function(data){ console.log("message received: " + data); this.msg = data; } } }
</script>

子元件程式碼如下。
1. 子元件無法直接改變父元件傳來的inputValue。因此,要自己建一個變數來將inputValue值傳給它。
2. 子元件使用watch來檢測inputValue的值的變化。
3. 子元件使用change事件來觸發向父元件傳遞訊息。但是不知道為啥只有按回車才會觸發change事件。有知道的告訴一下。謝謝!

<template>
  <div>
    <p>{{inputValue}}</p>
    <input type="text" v-model="msg" @change
="onInput">
</div> </template> <style></style> <script> export default{ props: { inputValue: String }, data () { return { msg: this.inputValue } }, watch: { inputValue: function(){ this.msg = this.inputValue } }, methods: { onInput: function(){ this.$emit('xxx', this.msg); console.log("message sent: " + this.msg); } } } </script>