当前页面向子组件传递的值带有HTML标签等非凡的字符时,传统的标签是无奈解析的,这时候就须要用插槽(solt)性能来传递变量值
ItemOne.vue子组件中通过solt
定义一个插槽
<template> <li class="item"> <input type="checkbox" v-model="checked" /> <!--插槽的名称和上面的属性名要对应--> <!--插槽将checked变量传递进来,不便调用者扭转变量值--> <slot name="comp" v-bind="{checked}"></slot> </li></template><script>export default { //属性名应该和插槽保持一致 props:['comp'], data(){ return { checked:false } }}</script><!--scoped示意css款式的作用域限度在以后文件中--><style scoped>.item{ color: red;}</style>
调用子组件
<template><div id="app"> {{msg}} <div> <!--v-model绑定到info变量上--> <input type="text" v-model="info"> <!--@click绑定点击事件--> <button @click="handle">增加</button> </div> <!--必须绑定:key :item示意组件ItemOne.vue的定义的变量,通过的属性的形式传递值到子组件--> <item-one v-for="item in list" :key="item"> <!-- v-slot绑定子组件的comp属性,并通过itemPros接管子组件传递过去的checked变量--> <template v-slot:comp="itemPros"> <!--子组件将checked的值传递进去,通过true和false来显示不同的字体色彩--> <span :style="{fontSize:'30px',color:itemPros.checked?'green':'blue'}">{{item}}</span> </template> </item-one></div></template><script>import ItemOne from './components/ItemOne'export default { name: 'App', data() { return { msg: "hello 入门小站", info: '', list: [] } }, methods: { handle(){ this.list.push(this.info); this.info=''; } }, components: { ItemOne }}</script><style>#app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px;}</style>
源码工程:https://github.com/mifunc/rum...