上文说到多个插槽会同时替换,解决方法:给插槽取名字加一个name。
我是分割线
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--作用让组件更具有拓展性
4.多个插槽,会同时替换 解决 给插槽加个name
-->
<template id="son">
<div>
<slot name="left">左边</slot>
<slot name="center">中间</slot>
<slot name="right">右边</slot>
</div>
</template>
<div id="app">
<!--指定插槽-->
<son><span slot="center">搜索框</span></son>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const son = {
template: '#son',
methods: {
sonClick(){
//通过$parent获取父组件
alert(this.$parent.message);
//通过$root获取根组件
alert(this.$root.movies);
}
},
};
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!',
},
components: {
son
},
});
</script>
</body>
</html>
 
我是分割线
前台效果:
Title 左边 中间 右边 搜索框