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

