Vue+

85 阅读2分钟

Vue+

组件

1.引入组件
import 名字 from "src地址" //写在script中
1.2注入组件
export default {
components:{
    组件名
    或者
    自定义名:组件名
}
}
1.3使用组件

注入后直接在模板中<组件名 /> 使用即可 如需使用slot 插槽 就写双标签

向组件内传入数据

温馨提示

props 注意只能进行父传子 不可子传父 也请了解props是只读的

父组件传递
<组件名 title='123'/>
当然也可以进行动态传递
export default {
...
message:20
...
}
<组件名 :tes1='message'/>
子组件接受
<script>
export default {
  props: ['title','tes1']
}
</script>

<template>
  <h4>{{ title }}</h4> //123
  <h4>{{ tes1 }}</h4> // 20
</template>
1.指定传入数据的类型
父组件传递
<组件名 title='123'/>
当然也可以进行动态传递
export default {
...
message:20
...
}
<组件名 :tes1='message'/>
子组件接受
<script>
export default {
  props:{
    message:{
        type: [String,Number],//支持 arr obj... 前面写法是传入两个其中一个都行
        default:0 //默认值如有值则不显示 
        /*如数组类型设置默认值则请使用
        default(){
        return ['空']
        }*/
        required:true //必须传值 否则警告
    }
}
}
</script>

<template>
  <h4>{{ title }}</h4> //123
  <h4>{{ tes1 }}</h4> // 20
</template>
1.2子传父 $emit

子传父 $emit('自定义事件名',携带的数据)

子组件传递
export default {

methods:{
postdata(){
this.$emit('tes1',this.message)//暴露了一个名为 tes1 的方法 并携带message数据一起发送
}
}
...
message:20
...
}
<button @click="postdata"> //使用点击事件
    发送
</button>
父组件接受
<script>
import 组件 from 'src地址'
export default {
  methods:{
getdata(date){ //形参data为 emit 携带的数据
    console.log(date) //20
}
  }
}
</script>
<template>
<组件名 @tes1="getdata"/>//接受后使用getdata得到数据
</template>

slot插槽

slot插槽 可从父组件中向子组件传入结构(模板)

<template>
  <father> //为引入的组件
    <h3>标题</h3>
  </father>
</template>
子组件
<template>
    <div>father</div>
    <slot></slot> //为父组件传递的内容 h3-标题
</template>
1.渲染作用域及默认内容

如果需要在插槽中添加动态数据请在父组件中声明

<template>
  <father> //为引入的组件
    <h3>{{ massage }}</h3>
  </father>
</template>
<scripyt>
...
massage:20    
...
</scripyt>
子组件
<template>
    <div>father</div>
    <slot>我是默认内容</slot> //20 如需添加默认内容直接在标签内写入即可
</template>
2.具名插槽

ps: 如有一个以上的插槽 请使用 具名插槽 v-solt 简写 #

<father>
    <template v-solt='header'>
   <div> {{ massage }} </div>
    </template>
    
    <template v-solt='main'>
    <p> 内容 </p>
    </template>
</father>

<script>
...
massage:20    
...
</script>
子组件
<template>
    <div>father</div>
    <slot name='header'>我是默认内容</slot> //20
    <slot name='main'>我是默认内容</slot> //内容
</template>
3.插槽数据传递
父
<template>
  <father v-slot="sondata"> //father为自定义组件 v-slot接收到子组件传递的数据 并存进 sondata
    <h3>{{ sondata.demo }}</h3>
  </father>
</template>
}
子
<template>
    <h3>son</h3>
    <slot :demo="datas"></slot> //向父组件暴露了 demo属性 值为20
</template>
<script>
...
datas:20
...
</script>

keep-alive 可使组件不被卸载

<keep-alive>
<组件></组件>
</keep-alive>

defineAsyncComponent 异步组件 使用时渲染

首先引入方法
import defineAsyncComponent from 'vue'
使用
const 名称 = defineAsyncComponent(()=>{
import('./组件地址')
})

跨组件传递数据

发送: provide

接收:inject

tips:

只能由上到下的传递!

provide(){ //发送

return{

数据:值

}

}
-----------------------
inject:['数据'] //接收