父组件向子组件传递参数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>父组件向子组件传递参数</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<btn-inc :my-name="username" :my-count="count"></btn-inc>
</div>
<script>
const vm=new Vue({
el:document.querySelector('#app'),
data(){
return {
username:'天涯明月刀',
count:0,
};
},
components:{
btnInc:{
//接受父组件传参
props:["myName","myCount"],
//父组件向子组件传值是单项的,不允许在子组件中更改父组件的值
template: `
<div>
<button @click="inc(1)">点赞 + {{num}}</button><span>{{myName}}</span>
</div>
`,
data(){
return { num:this.myCount, };
},
methods: {
inc(n){
this.num+=n;
}
},
},
}
});
</script>
</body>
</html>
效果:
父组件向子组件传递参数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>父组件向子组件传递参数</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<btn-inc :my-name="username" :my-count="count" @click-count="handle"></btn-inc>
</div>
<script>
//通过子组件更新父组件的值是通过事件来完成的
const vm=new Vue({
//子组件向父组件传参是通过同名事件来完成的
el:document.querySelector('#app'),
data(){
return {
username:'天涯明月刀',
count:0,
};
},
components:{
btnInc:{
//接受父组件传参
props:["myName","myCount"],
//父组件向子组件传值是单项的,不允许在子组件中更改父组件的值
//@emit(父组件中要使用的方法名称,子组件要传递给父组件的值)
template: `
<div>
<button @click="$emit('click-count',10)">点赞 + {{myCount}}</button><span>{{myName}}</span>
</div>
`,
data(){
return { num:this.myCount };
},
},
},
methods:{
handle(value){
console.log(this.count)
this.count+=value;
this.username='天涯明月刀续集';
},
},
});
//通过子组件更新父组件的值是通过事件来完成的
</script>
</body>
</html>
效果:
组件实现双向绑定
![](https://img.php.cn/upload/image/752/396/721/1611161685742561.png)