父组件向子组件传递值:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 父组件向子组件传地值 -->
<div id="app">
<!-- 子组件传递值,可以使用静态值,也可以使用动态值 -->
<son :num="count"></son>
<button @click="count++">加</button>
<button @click="count--">减</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
// 子组件
Vue.component('son', {
template: `
<div>
<div>父组件传递过来的值:num:{{num}} </div>
</div>
`,
// 使用props接收父组件传递的值,接收的num值子组件无法修改,只能父组件自己修改
props: ['num']
});
let app = new Vue({
el: "#app",
data: {
count: 0
}
});
</script>
</body>
</html>
子组件向父组件传值:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 子组件向父组件传递值 -->
<div id="app">
<div>子组件传递过来的值:{{count}} </div>
<son @add-one="fadd" @incr-one="fincr"></son>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
// 子组件
Vue.component('son', {
template: `
<div>
<div>子组件的值:{{num}}</div>
<button @click='add'>加</button>
<button @click='incr'>减</button>
</div>
`,
data() {
return {
num: 0
}
},
methods: {
add() {
this.num++
// 调用父组件的方法,并传递参数
this.$emit('add-one', this.num)
},
incr() {
this.num--
// 调用父组件的方法,并传递参数
this.$emit('incr-one', this.num)
}
}
});
let app = new Vue({
el: "#app",
data: {
count: 0
},
methods: {
fadd(num) {
this.count = num;
},
fincr(num) {
this.count = num;
}
}
});
</script>
</body>
</html>