Vue父子組件雙向數據綁定
阿新 • • 發佈:2018-10-28
2.4 div 問題本質 發生 通過 com one 允許 from
[本文出自天外歸雲的博客園]
簡介
Vue版本:2.9.6
Element版本:2.4.8
問題描述:子組件對Element中el-select進行封裝,父組件中把選中的值selected和所有選項options傳給子組件,當子組件中選中的option發生改變時,通知父組件並更新父組件中的selected值
問題本質:在子組件中接收父組件中傳遞過來的值A,當值A在子組件中發生改變,通知父組件並在父組件中更新值A
代碼
1. 父組件中引入並調用子組件,傳給子組件fatherSelected和fatherOptions兩個變量值,內容如下:
<template> <div> <SelectOption :selected.sync="fatherSelected" :options="fatherOptions"></SelectOption> </div> </template> <script> import { SelectOption } from ‘@/components/common‘ export default { name: ‘Father‘, data () { return { fatherOptions: [{‘label‘: ‘lab1‘, ‘value‘: ‘val1‘, ‘id‘:‘id1‘}, {‘label‘: ‘lab2‘, ‘value‘: ‘val2‘, ‘id‘:‘id2‘}], fatherSelected: ‘‘ } } } </script>
2. 路徑‘@/components/common‘下創建一個index.js文件導出子組件,內容如下:
export { default as SelectOption } from ‘./SelectOption‘
3. 子組件,用props定義從父組件接收傳參的變量selected和options,內容如下:
<template> <div class="selectOption"> <el-select v-model="mySelected" filterable @change="changeSelected"> <el-option v-for="option in options" :key="option.id" :label="option.label" :value="option.value"> </el-option> </el-select> </div> </template> <style> .selectOption { margin-top: 30px; } </style> <script> export default { props: [‘selected‘, ‘options‘], data: function () { return { mySelected: this.selected } }, methods: { changeSelected: function () { this.$emit(‘update:selected‘, this.mySelected) } } } </script>
註意事項
1. 子組件中接收父組件的值selected後,一定要保存到子組件作用域中的一個變量mySelected中
2. 當mySelected的值發生改變,@change監聽會觸發函數changeSelected執行
3. 通過thie.$emit來通知父組件進行update入參selected的值,對應更新父組件中的fatherSelected變量值
4. 對於允許子組件通知並進行改變的值fatherSelected一定要加 ".sync" 處理
Vue父子組件雙向數據綁定