Vue父子组件通信(父级向子级传递数据、子级向父级传递数据、Vue父子组件存储到data数据的访问)

时间:2023-03-09 04:41:54
Vue父子组件通信(父级向子级传递数据、子级向父级传递数据、Vue父子组件存储到data数据的访问)

Vue父子组件通信(父级向子级传递数据、子级向父级传递数据、Vue父子组件存储到data数据的访问)

一、父级向子级传递数据【Prop】:

Prop:子组件在自身标签上,使用自定义的属性来接收外界(也可以是父组件)的数据,然后将数据接收到prop中。【接收父组件的数据—动态Prop,需要v-bind绑定属性,数据可以从vue实例中获取】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>html暂时不支持驼峰写法</title>
</head>
<body>
<div id="app">
<!--
子组件要或者外界(例如也可以是父组件)的数据,它是需要在自身标签上,使用props中自定义的属性来接收,
若是想接收的数据来自父组件【Vue实例】------通过绑定属性(数据可以从vue实例中获取)
-->
<!--静态的prop-->
<cpn c-info="info"></cpn><br/>
<!--动态prop-->
<cpn :c-info="info"></cpn>
</div> <template id="cpn">
<div>
<h1>cpn的内容</h1>
<ul>
<li v-for="item in cInfo">{{item}}</li>
</ul>
</div>
</template>
</body> <script type="text/javascript" src="./js/vue.min.js"></script> <script>
const cpn = {
template: `#cpn`,
props:{
cInfo: {
type: Object,
default(){
return {}
}
}
},
} let app = new Vue({
el: '#app',
data: {
message:'动态绑定属性v-bind',
abc: {
id: '1',
name: '父类的info中的name',
age: '1'
},
info: {
id: '1',
name: '父类的info中的name',
age: '15'
}
},
components: {
cpn
}
});
</script>
</body>
</html>

二、子级向父级传递数据【emit】:

● 子组件通过$emit(‘自定义事件名’, 数据变量)向父组件发送消息,在子组件进行自定义的事件进行监听【监听调用的函数可以直接通过一个自定义的参数接收到数据变量】
<!-- 父组件 -->
<div id="app">
<!-- 子组件上监听到自定义的事件的同时,也监听到发送的数据num,事件指向的函数,通过自定义一个参数value可以直接拿到数据num -->
<cpn :c-info="info" @item-click="itemClick"></cpn>
</div>
<!-- 子组件的模板 -->
<template id="cpn">
<div>
<h1>子组件的模板</h1>
<button v-for="item in cInfo" @click="btnClick(item)">{{item}}</button>
</div>
</template>
</body> <script type="text/javascript" src="js/vue.min.js"></script> <script>
const cpn = {
template: `#cpn`,
data(){
return{
num: 99
}
},
props:{
cInfo: {
type: Object,
default(){
return {}
}
}
},
methods: {
btnClick(item){
console.log('子组件接收到父组件传递的数据' + item);
//$emit的第一个参数是自定义的事件名称和发送数据num
this.$emit('item-click', this.num);
}
}
} let app = new Vue({
el: '#app',
data: {
info: {
id: '1',
name: 'yile',
age: '15'
}
},
methods: {
itemClick(value){
console.log('父组件监听到子组件发出的事件和接收到子组件的数据' + value);
}
},
components: {
cpn
}
});
</script>

三、Vue父子组件存储数据的访问:

(1)父组件访问子组件data中存储的数据:使用$children或 $refs  (注意:this.$children得到的是一个数组,包含所有子组件对象。)

(2)$refs的使用:

$refs和ref指令通常是一起使用的

       ■ 首先,我们通过ref给某一个子组件绑定一个特定的ID

       ■ 其次,通过this.$refs.ID就可以访问到该组件了

Vue父子组件通信(父级向子级传递数据、子级向父级传递数据、Vue父子组件存储到data数据的访问)