父组件向子组件传递数据
如下,先在子组件中定义属性,然后父组件中必须在props数组中声明,然后即可以在子组件中进行使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue中组件的细节</title>
<script src="vue.js"></script>
</head>
<body>
<div id = 'app2'>
<row :count="1"></row>
<row :count="2"></row>
</div>
<script>
var row = {
props:['count'],
template:"<h2>{{count}}</h2>"
}
var app = new Vue({
el:'#app2',
components:{
row:row
}
});
</script>
</body>
</html>
如何在子组件中改变父组件中属性的值,错误示例如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue中组件的细节</title>
<script src="vue.js"></script>
</head>
<body>
<div id = 'app2'>
<row :count="1"></row>
<row :count="2"></row>
</div>
<script>
var row = {
props:['count'],
template:"<h2 @click='handleClick'>{{count}}</h2>",
methods:{
handleClick:function(){
this.count++;
}
}};
var app = new Vue({
el:'#app2',
components:{
row:row
}
});
</script>
</body>
</html>
下面演示父组件向子组件传递数据正确的形式
用法,先将属性里的值赋值给子组件中的一个变量然后改变该变量的值,再使用该变量
为什么不能直接改变父组件传递过来的属性的值呢,这里我们传递过来的是数值型,改变的话没有问题,但是若父组件属性中
是引用型并且多个组件都在使用呢?这个时候改变该属性的值必定会影响其他组件的属性值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue中组件的细节</title>
<script src="vue.js"></script>
</head>
<body>
<div id = 'app2'>
<row :count="1"></row>
<row :count="2"></row>
</div>
<script>
var row = {
props:['count'],
data:function(){
return {
number:this.count
}
},
template:"<h2 @click='handleClick'>{{number}}</h2>",
methods:{
handleClick:function(){
this.number++;
}
}};
var app = new Vue({
el:'#app2',
components:{
row:row
}
});
</script>
</body>
</html>
子组件向父组件中传值
此时我们可以在子组件中使用emit来触发父组件的事件来实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue中组件的细节</title>
<script src="vue.js"></script>
</head>
<body>
<div id = 'app2'>
<row :count="1" @getget="getTotal1"></row>
<row :count="2" @getget="getTotal1"></row>
{{total}}
</div>
<script>
var row = {
props:['count'],
data:function(){
return {
number:this.count
}
},
template:"<h2 @click='handleClick'>{{number}}</h2>",
methods:{
handleClick:function(){
this.number++;
this.$emit('getget',1);
}
}};
var app = new Vue({
el:'#app2',
components:{
row:row
},
data:{
total:3
},
methods:{
getTotal1:function(step){
alert(this.total);
this.total+=step;
}
}
});
</script>
</body>
</html>
本文深入讲解Vue.js中组件之间的通信机制,包括父组件向子组件传递数据、子组件向父组件传值的方法,以及如何避免修改父组件状态时可能引发的问题。

被折叠的 条评论
为什么被折叠?



