$parent
baseSon.vue
<template>
<div style="background-color: #999">
<h2>儿子金钱:{{ sonMoney }}</h2>
<button @click="giveFatherMoney(100)">给父亲100</button>
<button @click="subFatherMoney(5)">拿走父亲5块钱</button>
</div>
</template>
<script>
export default {
name: "baseSon",
props: ["fatherMoney"],
data() {
return {
sonMoney: 200,
};
},
methods: {
// giveFatherMoney(money) {
// this.$parent.fatherMoney += money;
// this.sonMoney -= money;
// },
giveFatherMoney (money) {
this.$parent.changeFatherMoney(money)
},
subFatherMoney (money) {
this.$parent.fatherMoney -= money
}
},
};
</script>
<style></style>
App.vue
<template>
<div class="app">
父亲的钱:{{ fatherMoney }}
<baseSon></baseSon>
<baseDau></baseDau>
</div>
</template>
<script>
import baseSon from './components/baseSon.vue';
import baseDau from './components/baseDau.vue';
export default {
components:{
baseSon,baseDau
},
data(){
return {
fatherMoney:10000
}
},
methods:{
changeFatherMoney(money){
this.fatherMoney += money
}
}
}
</script>
<style></style>
childern 不好用,所以建议$ref
ref
App.vue文章来源:https://www.toymoban.com/news/detail-731728.html
<template>
<div class="app">
父亲的钱:{{ fatherMoney }}
<button @click="getSonMoney(50)">父亲拿走儿的50元</button>
<button @click="giveSonMoney(100)">父亲给儿的100元</button>
<baseSon ref="baseSonRef" ></baseSon>
</div>
</template>
<script>
import baseSon from './components/baseSon.vue';
export default {
components:{
baseSon
},
data(){
return {
fatherMoney:10000
}
},
methods:{
changeFatherMoney(money){
this.fatherMoney += money
},
getSonMoney(money){
console.log('getSonMoney');
// this.$children.sonMoney -= money
this.$refs.baseSonRef.sonMoney -= money
// console.log('this.$children.sonMoney', this.$children.sonMoney);
},
giveSonMoney(money){
this.$refs.baseSonRef.changeSonMoney(money)
// this.$children.changeSonMoney(money)
}
}
}
</script>
<style></style>
baseSon.vue文章来源地址https://www.toymoban.com/news/detail-731728.html
<template>
<div style="background-color: #999">
<h2>儿子金钱:{{ sonMoney }}</h2>
<button @click="giveFatherMoney(100)">给父亲100</button>
<button @click="subFatherMoney(5)">拿走父亲5块钱</button>
</div>
</template>
<script>
export default {
name: "baseSon",
props: ["fatherMoney"],
data() {
return {
sonMoney: 200,
};
},
methods: {
// giveFatherMoney(money) {
// this.$parent.fatherMoney += money;
// this.sonMoney -= money;
// },
giveFatherMoney(money) {
this.$parent.changeFatherMoney(money)
},
subFatherMoney(money) {
this.$parent.fatherMoney -= money
},
changeSonMoney(money) {
this.sonMoney += money
}
},
};
</script>
<style></style>
到了这里,关于$parent 和 $children的用法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!