Vue中的组件传值
默认情况下,components属性中的组件无法访问data中的数据和methods中的方法
1.父组件通过props属性来实现向子组件传值
- 定义子组件
var vm=new Vue({
components:{
coml:{
template:'<p>{{parentmsg}}</p>'
}
}
})
- 定义父数据
var vm=new Vue({
el:'#app',
data:{
msg:'a'
}
})
- 将父组件数据引入到子组件
<div id="#app">
<coml v-bind:parentmsg="msg">
<!--v-bind:可以简写为:-->
</coml>
</div>
v-bind:后面的名称就是数据的名称
- 定义子组件props
新增一个props属性
var vm=new Vue({
components:{
coml:{
props:['parentmsg']
}
}
})
与components中的data的区别:
props是从父组件传递过来的,只能读取,不能修改父组件中的值
data是子组件私有的,可读可写
2.通过父组件向子组件传递方法来实现子组件向父组件传值传值
跟异步跨域访问类似,因为父组件的方法可以传递到子组件,子组件可以使用父组件的方法,所以可以传递一个参数给父组件进行处理
- 定义子组件
var vm=new Vue({
components:{
coml2:{
template:'<input type="button" value="show" @click="myshow"/>'
}
}
})
- 定义父组件的方法
var vm=new Vue({
el:'#app',
methods:{
show(data){
//父组件对传回的data进行处理
}
}
})
- 将父组件的方法引入到子组件
<div id="app">
<coml2 v-on:parentshow="show">
<!--v-on:可以简写为@-->
</coml2>
</div>
- 定义子组件的methods
var vm=new Vue({
components:{
coml:{
methods:{
myshow(){
this.$emit('parentshow',需要传递的数据)
}
}
}
}
})
3.父组件通过ref获取子组件的数据
ref获取DOM元素和组件
vue提供了一个refs数组,存储了DOM元素的节点id
可以加在标签和组件上
- 在标签上加上属性ref
<p ref="a"></p>
- 获取DOM元素
this.$refs.a
具体使用
- 定义子组件
var vm=new Vue({
components:{
coml3:{
template:'<p>子组件</p>',
data:{
msg:'子组件上的数据'
}
}
}
})
- 在标签上加上ref属性
<coml3 ref="一个ID"></coml3>
- 父组件获取子组件中的数据
var vm=new Vue({
el:'#app',
methods:{
show(){
console.log(this.$refs.一个ID.msg)
}
}
})
4.父组件通过ref向子组件传递数据
- 定义子组件
var vm=new Vue({
components:{
coml4:{
template:'<p>子组件</p>',
data(){
return{msg:'子组件上的数据'}
},
methods:{
receive(data){
this.msg=data
}
}
}
}
})
- 在标签上加上ref属性
<coml4 ref="一个ID"></coml4>
- 父组件调用子组件中的方法,实现传值
var vm=new Vue({
el:'#app',
data:{
msg:'父组件的数据'
},
methods:{
send(){
console.log(this.$refs.一个ID.receive(this.msg))
}
}
})
- 调用父组件中的方法
<input type="button" @click="send"/>
总结:
对比传递数据:
前两种方式比较麻烦,但是传递的数据可以不只是data中的数据。
第一种方式是由父组件向子组件传递
第二种方式是由子组件向父组件传递
第三种方式比较简单,只用一个id即可获取数据,就能向父组件传递子组件data中的数据
第四种方式比较简单,使用父组件调用子组件中的方法,实现向子组件传递父组件data中的数据
对比传递方法:
第一种方式无法传递
第二种方式比较麻烦,只能由父组件传递方法给子组件调用
第三种方法无法传递
第四种方法比较简单,只能由子组件传递方法给父组件调用
|你知道的越多,不知道的越多。 |如果本文章内容有问题,请直接评论或者私信我。如果觉得写的还不错的话,点个赞也是对我的支持哦。 |未经允许,不得转载!|微信搜【程序员徐小白】,关注即可第一时间阅读最新文章。回复【面试题】有我准备的50道高频校招面试题,以及各种学习资料。

浙公网安备 33010602011771号