父组件向子组件传值
组件中可以用props来声明需要从父级接收的数据。
props和data、method平级,有两种方式:
1. 字符串数组方式,数组中的字符串就是传递时的名称
<div id="app">
<!-- 第一步 使用bind绑定的方式 将父类的组件中的数据传给子组件 -->
<parent :msg="msg"></parent>
</div>
<template id="temp">
<h2>title{{msg}}</h2>
</template>
<script type="text/javascript">
let parent=Vue.extend({
template:'#temp',
data(){
return {
msg:'默认'
}
},
//第二步 使用props接收数据
props:[
"msg"
]
})
var app=new Vue({
el:"#app",
data:{
msg:'我是父组件msg'
},
components:{
parent
}
})
</script>
2. 对象方式,对象方式可以设置类型和默认值(一般开发用对象方式)
<div id="app">
<parent :msg="msg"></parent>
</div>
<template id="temp">
<h2>title{{msg}}</h2>
</template>
<script type="text/javascript">
let parent=Vue.extend({
template:'#temp',
data(){
return {
msg:'默认'
}
},
// props对象的方式给子组件传值
props:{
msg:{
type:String,
default:'我是默认值,父组件没有给我传数据'
}
}
})
var app=new Vue({
el:"#app",
data:{
msg:'我是父组件msg'
},
components:{
parent
}
})
</script>
3. 父组件向子组件传递方法
<div id="app">
<comp @compmethodmsg="alertMsg"></comp>
</div>
<template id="tmp">
<button @click="handlerMethod">点我</button>
</template>
<script type="text/javascript">
let comp=Vue.extend({
template: "#tmp",
methods:{
handlerMethod(){
//第一个参数表示要调用的方法
//第二个参数表示要传递的参数
this.$emit("compmethodmsg","调用")
}
}
})
let app=new Vue({
el:"#app",
data:{},
methods:{
alertMsg(msg){
alert(msg);
}
},
components:{
comp
}
})
</script>
4. 父组件调用子组件方法
$refs是ref一起用的。通过ref给某个子组件绑定一个特有的ID,然后用$refs.ID就可以访问到子组件了。
<div id="app">
<button @click="countAdd">点我</button>
<!-- 第一步 给子组件绑定ref -->
<comp ref="myRef"></comp>
</div>
<template id="tmp">
<h1>{{count}}</h1>
</template>
<script type="text/javascript">
let comp=Vue.extend({
template: "#tmp",
data(){
return {
count:1
}
},
methods:{
addCount(){
this.count++
}
}
})
let app=new Vue({
el:"#app",
methods:{
countAdd(){
//第二步 在父组件使用this.$refs.ID就能获得
this.$refs.myRef.count++
}
},
components:{
comp
}
})
</script>