零基础学习Vue: 第26课 Vue作用域插槽子组件向父主件传递数据:
子组件传递数据:
<!-- 子组件设置slot插槽 (:aaa="arr":将子组件的arr数据传递给父主件,设置传递的属性名:aaa) -->
<slot :aaa="arr" ></slot>
父组件接收子组件的数据:
<!-- 必须要用template标签 必须要用slot-scope属性 来接收子组件插槽传递过来的数据 -->
<!-- 传递过来的数据都在result中 在template标签内可以使用接收的数据-->
<template slot-scope="result"> </template>
示例1 接下来我们来看演示代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 引入vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 5.引用子主件 -->
<son>
<!-- 6.必须要用template标签 必须要用slot-scope属性 来接收子组件插槽传递过来的数据 -->
<template slot-scope="result">
<ul>
<!-- 7.子组件的数据都存在result中,这是规定的 传递过来的数据的属性名为admin 我们通过v-for遍历数据-->
<li v-for="(item,index) in result.aaa">
{{index}}----{{item}}
</li>
</ul>
</template>
</son>
</div>
<!-- 3.设置子组件son标签 -->
<template id="son">
<div>
<!-- 4.子组件设置slot插槽 (:aaa="arr":将子组件arr数据传递给父主件,设置属性名:aaa) -->
<slot :aaa="arr" ></slot>
{{a}}
</div>
</template>
<script>
//1.定义子组件son
let son = {
template:'#son',
data(){ //子组件内的数据
return {
a:'我是子组件的数据',
arr:['吃饭','上课','睡觉']
}
}
}
let vm = new Vue({
el:'#app',
components:{ //2.在根主件内注册子组件son
son
},
})
</script>
</body>
</html>
示例1 运行结果如下:
示例2 接下来我们通过子组件插槽一次性传递多个数据,并且父组件多次接收:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 引入vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 5.引用子主件 -->
<son>
<!-- 6.必须要用template标签 必须要用slot-scope属性 来接收子组件插槽传递过来的数据 -->
<template slot-scope="result">
<ul>
<!-- 7.子组件的数据都存在result中,这是规定的 传递过来的数据的属性名为admin 我们通过v-for遍历数据-->
<li v-for="(item,index) in result.aaa">
{{index}}----{{item}}
</li>
</ul>
</template>
</son>
<!-- 下面我们再次用一个template进行获取子主件插槽传来的数据 -->
<son>
<template slot-scope="result">
<span v-for="(item,index) in result.aaa">
{{index}}----{{item}}
</span>
<ul>
<li v-for="(item,index) in result.bbb">
{{index}}----{{item}}
</li>
</ul>
</template>
</son>
</div>
<!-- 3.设置子组件son标签 -->
<template id="son">
<div>
<!-- 4.子组件插槽向父主件传递两个数据 -->
<slot :aaa="arr" :bbb="arr2"></slot>
{{a}}
</div>
</template>
<script>
//1.定义子组件son
let son = {
template:'#son',
data(){ //子组件内的数据
return {
a:'我是子组件的数据',
arr:['吃饭','上课','睡觉'],
arr2:['小猫','小狗','小鱼']
}
}
}
let vm = new Vue({
el:'#app',
components:{ //2.在根主件内注册子组件son
son
},
})
</script>
</body>
</html>
示例2 运行结果如下:
那子组件传递参数给父组件有什么作用呢?为何不直接在子组件内直接写上子组件的数据?
答案:因为子组件是固定主件写上后不方便更改,而在父组件接收子组件的数据可以通过数据设置任意的标签样式!