vuejs2.0子組件改變父組件的數(shù)據(jù)實(shí)例
在vue2.0之后的版本中,不允許子組件直接改變父組件的數(shù)據(jù),在1.0的版本中可以這樣操作的,但是往往項(xiàng)目需求需要改變父組件的數(shù)據(jù),2.0也是可一個(gè),區(qū)別是,當(dāng)我們把父元素的數(shù)據(jù)給子組件時(shí),需要傳一個(gè)對象,子組件通過訪問對象中的屬性操作數(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ù),就是說子組件的數(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>
這里巧妙的通過mounted這個(gè)方法進(jìn)行了中轉(zhuǎn),實(shí)現(xiàn)了想要的效果
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決使用Vue.js顯示數(shù)據(jù)的時(shí),頁面閃現(xiàn)原始代碼的問題
下面小編就為大家分享一篇解決使用Vue.js顯示數(shù)據(jù)的時(shí),頁面閃現(xiàn)原始代碼的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02
vue 屬性攔截實(shí)現(xiàn)雙向綁定的實(shí)例代碼
這篇文章主要介紹了vue 屬性攔截實(shí)現(xiàn)雙向綁定的實(shí)例代碼,代碼簡答易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-10-10
vue實(shí)現(xiàn)點(diǎn)擊按鈕切換背景顏色的示例代碼
這篇文章主要介紹了用vue簡單的實(shí)現(xiàn)點(diǎn)擊按鈕切換背景顏色,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
vue2.0+vuex+localStorage代辦事項(xiàng)應(yīng)用實(shí)現(xiàn)詳解
本篇文章給大家分享了一個(gè)用vue2.0+vuex+localStorage代辦事項(xiàng)應(yīng)用實(shí)現(xiàn)的代碼過程,有興趣的朋友跟著參考學(xué)習(xí)下。2018-05-05
vue+element-ui表格自定義列模版的實(shí)現(xiàn)
本文主要介紹了vue+element-ui表格自定義列模版的實(shí)現(xiàn),通過插槽完美解決了element-ui表格自定義列模版的問題,具有一定的參考價(jià)值,感興趣的可以了解一下2024-05-05
vue實(shí)現(xiàn)移動(dòng)端輕量日期組件不依賴第三方庫的方法
這篇文章主要介紹了vue 移動(dòng)端輕量日期組件不依賴第三方庫,需要的朋友可以參考下2019-04-04

