1.父组件向子组件通过自定义参数传参
<div id="app">
<btn-inc :my-name="username" :my-count="count"></btn-inc>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const vm = new Vue({
el: '#app',
data() {
return {
username: '天蓬大人',
count: 0,
}
},
// 局部组件
components: {
btnInc: {
props: ["myName", "myCount"],
template: `
<div>
<button @click="num++">点赞:+ {{num}}</button>
<span>{{myName}}</span>
</div>
`,
data() {
return {
num: this.myCount,
};
}
}
}
})
</script>
2.子组件向父组件通过自定义方法传参
<div id="app">
<btn-inc :my-name="username" :my-count="count" @click-count="handle"></btn-inc>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const vm = new Vue({
el: '#app',
data() {
return {
username: '天蓬老师',
count: 0,
};
},
// 局部组件
components: {
btnInc: {
props: ["myName", "myCount"],
template: `
<div>
<button @click="$emit('click-count',10)">点赞:+ {{myCount}}</button>
<span>{{myName}}</span>
</div>
`,
},
},
// 子组件更新父组件的自定义方法
methods: {
handle(value) {
console.log(this.count);
this.count += value;
this.username = "天蓬大人";
}
},
})
</script>