国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 金堂县| 祁连县| 阳山县| 石河子市| 连山| 布尔津县| 手游| 罗城| 申扎县| 界首市| 华容县| 上杭县| 吉林市| 琼中| 九寨沟县| 都匀市| 原阳县| 闻喜县| 聂荣县| 娄烦县| 井研县| 东安县| 滦南县| 嘉禾县| 德令哈市| 景德镇市| 惠东县| 海伦市| 正定县| 罗田县| 城固县| 平顺县| 大同县| 镶黄旗| 大连市| 台北县| 沾益县| 孝昌县| 阿拉尔市| 靖安县| 石嘴山市|