Vue—子级向父级传递数据
Posted 每天都在慢慢进步的王同学
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue—子级向父级传递数据相关的知识,希望对你有一定的参考价值。
【Vue】—子级向父级传递数据
<template>
<div>
<h2>Son</h2>
<div v-for='(item,index) in data' :key='index'>
<div>
<img :src="item.picurl" alt="">
</div>
<div>
<p>{{item.title}}</p>
<p>{{item.year}}年</p>
</div>
</div>
<p>msg:{{msg}}</p>
<p>number:{{number}}</p>
<p>user:{{obj.user}}</p>
<p>age:{{obj.age}}</p>
<p>游戏:{{game}}</p>
<button @click="clickme">获取this</button>
<button @click="sendData">把子级数据传递给父级</button>
<button @click="sendData2">emit()</button>
</div>
</template>
<script>
export default {
data() {
return {
count: '999'
}
},
//props: ['data']
props: {
getdata: Function,
data: Array,
msg: [String, Number, Boolean],
obj: {
type: Object,
required: true,
default: function () {
return {
user: 'admin',
age: 0
}
}
},
number: {
type: [Number, String],
default: 100
},
game: {
validator: function (value) {
let arr = ['CF', '和平', 'LOL'];
return arr.indexOf(value) !== -1;
}
}
},
methods: {
clickme() {},
sendData() {
this.getdata(this.count);
},
sendData2() {
this.$emit('getSonData', this.count, 1, 2, 4);
}
}
}
</script>
<style>
</style>
<template>
<div>
<h2>Parent</h2>
<!-- 父子传递数据 -->
<Son :data='arr' msg='msg数据' :obj="obj" :number='number' :game='game' :getdata='getdata'
@getSonData='getSonData' />
</div>
</template>
<script>
import Son from './Son';
export default {
components: {
Son
},
methods: {
getdata(cs) {
console.log(cs);
},
getSonData(...rest) {
console.log(rest);
}
},
data() {
return {
game: 'CF',
number: 1,
obj: {
user: 'Lily',
age: 18
},
arr: [{
title: '王嘉尔',
year: 2021,
picurl: 'https://pics2.baidu.com/feed/0d338744ebf81a4c633b6aa4fd3a5d5f252da66c.jpeg?token=11476c18354c409e2b80b5c2e6c5d3b1&s=BA8AF205CE6258947A3C2ED903005094'
},
{
title: '王一博',
year: 2020,
picurl: 'https://pics2.baidu.com/feed/0d338744ebf81a4c633b6aa4fd3a5d5f252da66c.jpeg?token=11476c18354c409e2b80b5c2e6c5d3b1&s=BA8AF205CE6258947A3C2ED903005094'
}
]
}
}
}
</script>
<style>
</style>
以上是关于Vue—子级向父级传递数据的主要内容,如果未能解决你的问题,请参考以下文章