在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)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注