国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > JavaScript > 正文

vuejs2.0子組件改變父組件的數(shù)據(jù)實(shí)例

2019-11-19 16:37:04
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

在vue2.0之后的版本中,不允許子組件直接改變父組件的數(shù)據(jù),在1.0的版本中可以這樣操作的,但是往往項(xiàng)目需求需要改變父組件的數(shù)據(jù),2.0也是可一個(gè),區(qū)別是,當(dāng)我們把父元素的數(shù)據(jù)給子組件時(shí),需要傳一個(gè)對(duì)象,子組件通過(guò)訪問(wèn)對(duì)象中的屬性操作數(shù)據(jù),下面是演示

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>Document</title>  <script type="text/javascript" src="vue.js"></script>    <script type="text/javascript">    window.onload = function(){      var app = new Vue({      el:'#box',      data:{        myData:{          info:'父組件信息'        }      },      components:{        'v-com':{          props:['data'],          template:'#tpl',          methods:{            change(){              this.data.info = 'change info'            }          }        }      }    })    }  </script></head><body>  <!-- 子組件改變父組件的數(shù)據(jù) -->  <div id="box">    <div>      <p>{{myData.info}}</p>      <v-com :data ="myData"></v-com>    </div>  </div>  <!-- 模板 -->  <template id="tpl">    <div>      <button @click="change">change</button>      <p>{{data.info}}</p>    </div>  </template></body></html>

這種是同步改變數(shù)據(jù),就是說(shuō)子組件的數(shù)據(jù)改變,父組件數(shù)據(jù)也跟著改變,下面展示非同步的情況

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>Document</title>  <script type="text/javascript" src="vue.js"></script>    <script type="text/javascript">    window.onload = function(){      var app = new Vue({      el:'#box',      data:{        myData:'父組件信息'      },      components:{        'v-com':{          data() {            return {              childData:''            }          },          props:['data'],          // dom渲染完畢          mounted(){            this.childData = this.data          },          template:'#tpl',          methods:{            change(){              this.childData = 'change info'            }          }        }      }    })    }  </script></head><body>  <!-- 子組件改變父組件的數(shù)據(jù),不同步 -->  <div id="box">    <div>      <p>{{myData}}</p>      <v-com :data ="myData"></v-com>    </div>  </div>  <!-- 模板 -->  <template id="tpl">    <div>      <button @click="change">change</button>      <p>{{childData}}</p>    </div>  </template></body></html>

這里巧妙的通過(guò)mounted這個(gè)方法進(jìn)行了中轉(zhuǎn),實(shí)現(xiàn)了想要的效果

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 蓝山县| 县级市| 田林县| 安新县| 稻城县| 探索| 嘉祥县| 新竹市| 泌阳县| 镶黄旗| 淮滨县| 县级市| 鄂尔多斯市| 克拉玛依市| 高碑店市| 临武县| 阿拉尔市| 潞城市| 伊金霍洛旗| 濉溪县| 虎林市| 禹州市| 麻城市| 日照市| 喀什市| 开化县| 库尔勒市| 隆安县| 霍城县| 高淳县| 荔波县| 横峰县| 黑水县| 明星| 上栗县| 乌审旗| 霍山县| 河津市| 香格里拉县| 阳高县| 平南县|