wyangnb

父组件给子组件传值【props】

1.首先在父组件的script标签中引入子组件
import Children from './Children'
2.在template内引入子组件

3.将要传递的参数写在Children里

<Children
:parameterName1="parameterVal1"
:parameterName2="parameterVal2"
...

4.然后在子组件中使用props接受

//html
<div :title="parameterName1">{{parameterName1}}


// js
props:{
parameterName1:{
type:String,
default:''
},
parameterName2:{
type:Number, //期待接收的数据类型,如果类型传错,vue将抛出异常
default:''
}
},
created() {
console.log(this.parameterName1) //可以在生命周期钩子中直接使用
},
methods:{
fun:function(){
console.log(this.parameterName2) //可以在生命周期钩子中直接使用
}
}
## 子组件给父组件传值【$emit】
1.首先在父组件内自定义一个事件

//html
<Children @clickItem="backList">

//js
backList:function (item) { //item为子组件传过来的数据
this.showChild = item;
console.log(item); //true
}

2.然后在子组件内使用$emit来触发父组件中的自定义方法

//html
<button @click="back(true)">点我一下试试 //back方法内的参数‘true’是要传递给父组件的数据

//js
back:function (isShow) {
this.\(emit('clickItem',isShow); //注意:第一个参数必须是父组件中自定义的事件名(必须保持一直),第二个参数为子组件要给父组件传递的参数 } ``` ## 路由跳转传参【params】 ``` this.\)router.push({
path: '/play',
name: 'Play',
params:{
songmid:this.songmid,
songs:this.songs
}
})
## 接受路由参数【$route】this.\(route.params.songmid; //注意是\)route 而不是\(router ; 添加路由的时候才用\)router```

slot

单个slot

1.首先在子组件内设定slot标签

<template>
  <slot>占个坑先</slot>
</template>

2.然后在父组件内引入子组件

<Children></Children>  <!--输出:占个坑先-->    注意:slot可以在父组件内缺省,缺省的话就是使用子组件内slot的值

<Children>
  <span>这个坑归父组件使用了</span>  <!--输出:这个坑归父组件使用了-->
</Children>

具名slot

1.首先在子组件内设定slot标签,并且slot标签上设定具体的name属性

<template>
  <slot name="keng">占个坑先</slot>
</template>

2.然后在父组件内引入子组件

<Children>
  <span :slot="keng">这个坑归父组件使用了</span>  <!--输出:这个坑归父组件使用了-->  注意:span标签的slot属性必须写,而且属性值必须要和子组件内slot的name值一样
</Children>

分类:

技术点:

相关文章: