如果子组件想使用父组件的data时:
<div id="app">
<aa :smsg="msg"></aa> 先在标签中创建一个变量绑定父组件中的data中的属性
</div>
<script>
Vue.component('aa',{
template:'<p>我是子组件中的PPP+++{{smsg}}</p>', 最后就可以在组件中使用data值了
props:['smsg'] 然后在props中,存放变量名
})
var vm=new Vue({
el:'#app',
data:{
msg:'我是父组件中的msg'
}
})
</script>
注意:在props里如果需要在methods中对中的数据修改时,可以先在子组件的data中创建一个变量,在用其来操作methods
<div id="app">
<aa :smsg="msg" :scon="con" @sfn="father"></aa> 先在标签上绑定一个函数使其等于父组件中的函数
</div>
<script>
Vue.component('aa',{
template:'<p>{{cont}}__我是子组件中的PPP+++{{smsg}}<button @click="show">按钮</button><button @click="add">+++</button></p>',
先把父组件中的con赋予个scon,再在子组件中的data中让cont等于scon,之后就可以在methods中操作cont了
props:['smsg','scon'] ,
data:function(){
return {
cont: this.scon
}
},
methods: {
show:function () {
this.$emit('sfn') 在子组件中再创建一个函数,并使用this.$emit('xx')就可以使用父组件中的函数了;
},
add:function () {
this.cont++
}
}
})
var vm=new Vue({
el:'#app',
data:{
msg:'我是父组件中的msg',
con:1,
},
methods:{
father:function () {
console.log('我是父组件中的方法');
}
}
})
</script>
如果父组件中的函数有参数的话,this.$emit('函数名',参数1,参数2,参数3...)
<div id="app">
<aa @sfn="father"></aa>
</div>
<script src="../vue.js/vue.js"></script>
<script>
Vue.component('aa',{
template:'<p>我是子组件中的PPP+++<button @click="show">子按钮</button></p>',
data:function(){
return {
smsg:'我是子组件中的smsg'
}
},
methods: {
show:function () {
this.$emit('sfn',this.smsg) 在此传参,可以把子盒子中的值,传给父盒子
},
}
})
var vm=new Vue({
el:'#app',
data:{
con:1,
ff:'',
},
methods:{
father:function (data) { 接受到了子盒子的值,并赋予data上
this.ff=data
}
}
})
</script>