父组件向子组件传值
- 组件实例定义方式,注意:一定要使用
props
属性来定义父组件传递过来的数据 - 使用
v-bind
或简化指令,将数据传递到子组件中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1" rel="stylesheet" type="text/css">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 使用v-bind或简化指令,将数据传递到子组件中 -->
<son :father="msg" :father2="msg2"></son>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
msg:'父组件数据',
msg2:'父组件2'
},
methods: {},
components:{
son:{
template:'<h1>我是子组件:使用---{{father}} ---- {{father2}}</h1>',
props:['father','father2']
}
}
});
</script>
</body>
</html>
展示效果:
子组件向父组件传值
- 原理:父组件将方法的引用,传递到子组件内部,子组件在内部调用父组件传递过来的方法,同时把要发送给父组件的数据,在调用方法的时候当作参数传递进去;
- 父组件将方法的引用传递给子组件,其中,
getMsg
是父组件中methods
中定义的方法名称,func
是子组件调用传递过来方法时候的方法名称 - 子组件内部通过
this.$emit('方法名', 要传递的数据)
方式,来调用父组件中的方法,同时把数据传递给父组件使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1" rel="stylesheet" type="text/css">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 使用v-bind或简化指令,将数据传递到子组件中 -->
<son @father="getMsg"></son>
</div>
<!-- 组件模板定义 -->
<script type="x-template" id="son">
<div>
<input type="button" value="向父组件传值" @click="sendMsg" />
</div>
</script>
<script>
// 子组件的定义方式
Vue.component('son', {
template: '#son', // 组件模板Id
methods: {
sendMsg() { // 按钮的点击事件
this.$emit('father', 'OK'); // 调用父组件传递过来的方法,同时把数据传递出去
}
}
});
var vm = new Vue({
el: '#app',
data: {
},
methods: {
getMsg(val){ // 子组件中,通过 this.$emit() 实际调用的方法,在此进行定义
alert(val)
}
}
});
</script>
</body>
</html>
效果展示:点击按钮,弹窗获取子组件的数据