Vue作用域插槽
编译作用域的理解:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>编译作用域</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<cpn v-show="isShow"></cpn>
</div>
<template id="cpn">
<div>
<h2>我是子组件</h2>
<p>我是子组件的内容!</p>
<button v-show="isShow">按钮</button>
</div>
</template>
<script>
const app = new Vue({
el:"#app",
data:{
msg:"你好世界!Hello World!",
isShow: true
},
components:{
cpn:{
template: "#cpn",
data(){
return{
isShow: false
}
}
}
}
})
</script>
</body>
</html>
显示则说明是父组件中的变量,然后f12,app.isShow = false消失则说明父组件变量起作用.按钮无法显示,说明子组件不能访问父组件变量,父组件也不能直接的访问子组件的变量.
总结:父组件模板所有东西都会在父级作用域内编译,子组件模板的所有东西都会在子级作用域编译.
作用域插槽是slot一个比较难理解的点,而且官方文档解释的不是太清楚
个人的理解是:
父组件替换插槽的标签,但是内容是由子组件来提供的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>编译作用域</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<cpn></cpn>
<cpn>
<template slot-scope="slot">
<span v-for="item in slot.data">{{ item }}- </span>
</template>
</cpn>
</div>
<template id="cpn">
<div>
<slot :data="pLanguages">
<ul>
<li v-for="item in pLanguages" > {{ item }}</li>
</ul>
</slot>
</div>
</template>
<script>
const app = new Vue({
el:"#app",
data:{
msg:"你好世界!Hello World!",
isShow: true
},
components:{
cpn:{
template: "#cpn",
data(){
return{
pLanguages: ['Java','GO','Swift','C']
}
}
}
}
})
</script>
</body>
</html>
流程:子组件中的数据展示,不是父组件想要的,父组件想办法拿到子组件数据按照自己格式展示的过程.