1.创建组件
找到components文件,在下面创建一个以.vue为后缀的组件。
组件中包括三个部分。
1.template 组件构成
2.script 组件js部分
3.style 组件样式,若添加scope,则样式只在当前组件中生效。
<template>
<div>
small1组件
<!--将组件挂载到页面中-->
<small2 />
</div>
</template>
<script>
// 在当前组件中引入其他组件
import small2 from './small2'
export default {
name: "small1",
// 申明引入的组件,es6写法,也可写为 small2:small2
components: {
small2
}
}
</script>
<style scoped>
</style>
2.组件中插槽slot的使用(父组件向子组件传送页面元素)
组件之间,存在父子关系。当在parent组件中,要嵌入child组件时。直接在parent组件中引入,页面挂载<child />,即可。
若需要运用到插槽,则
<child class="childPart">
<!--插槽内容-->
<p slot="s1">{{msg1}}</p>
<!--接受子传来的数据-->
<p slot="s2" slot-scope="value">{{value.text}}</p>
</child>
子组件中
<div>
我是子组件
<slot name="s1">没有定义插槽内容</slot>
<hr>
<!--插槽像父传递数据-->
<slot name="s2" :text="text">没有定义插槽内容</slot>
</div>
具名插槽
上述代码所示,当需要在组件中插入多个插槽时,给每个插槽一个name属性的值,父级传入的元素通过slot来接受相对应的插槽名称。
子组件中的<slot></slot>可进行重复使用。
作用域插槽 (子组件向父组件通过元素属性的值来进行数据传递)
上述代码所示,子组件将数据通过text属性向父组件传递,父组件中通过slot-scope属性来接收子组件传递过来的信息,展示到页面当中。
这种父组件和子组件的数据传递方式仅用于slot插槽当中。
3.动态组件
页面中如需通过某个值动态渲染组件,可通过动态绑定属性is来处理
<template>
<div>
<keep-alive>
<component :is="name"></component>
</keep-alive>
</div>
</template>
<script>
import hello from './HelloWorld'
import douban from './doubanAxios'
export default {
name: "isComponent",
data(){
return{
name:"douban"
}
},
components:{
hello,
douban
}
}
</script>
<style scoped>
</style>
组件缓存keep-alive
如果需要动态渲染的组件,上面所加载的数据短时间内不会持续更新,可以给组件添加缓存,此时组件的渲染就不需要被重新的渲染,而是根据缓存来回切换。如上述代码。










网友评论