1.父组件向子组件传值:通过props进行通信
- 在子组件中声明
props接收在父组件挂载的属性。
- 可以在
子组件的template中任意使用
- 在
父组件绑定自定义的属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<App></App>
</div>
<script src="./vue.js"></script>
<script>
Vue.component('Child',{
template:`
<div>
<h3>我是一个子组件</h3>
<h4>{{childData}}</h4>
</div>
`,
props:['childData']
})
const App = {
data() {
return {
msg: '我是父组件传进来的值'
}
},
template: `
<div>
<Child :childData = 'msg'></Child>
</div>
`,
computed: {
}
}
new Vue({
el: '#app',
data: {
},
components: {
App
}
})
</script>
</body>
</html>
1.1子组件props接收的两种形式
props可以是数组
props可以是对象,当props是对象的时候,可是设置规定传递过来的值的类型和默认值
<template>
<div>
<div>我是子组件</div>
<p>{{sendContent}}</p>
</div>
</template>
<script>
export default {
data() {
return {
text: '我是子组件中的元素',
};
},
props: {
sendContent: {
type: String,
default: "我是默认值"
}
}
};
</script>
<style lang="scss" scoped>
</style>
2.子组件向父组件传值
- 在父组件中的子组件上绑定自定义事件
@inputHandler = 'input'
- 在子组件中 触发原生的事件 在事件函数通过
this.$emit触发自定义的事件inputHandler
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>子组件向父组件传值</title>
</head>
<body>
<div id="app">
<App></App>
</div>
<script src="./vue.js"></script>
<script>
Vue.component('Child', {
template: `
<div>
<h3>我是一个子组件</h3>
<h4>{{childData}}</h4>
<input type="text" @input = 'handleInput'/>
</div>
`,
props: ['childData'],
methods:{
handleInput(e){
const val = e.target.value;
this.$emit('inputHandler',val);
}
},
})
const App = {
data() {
return {
msg: '我是父组件传进来的值',
newVal:''
}
},
methods:{
input(newVal){
this.newVal = newVal;
}
},
template: `
<div>
<div class='father'>
数据:{{newVal}}
</div>
<Child :childData = 'msg' @inputHandler = 'input'></Child>
</div>
`,
computed: {
}
}
new Vue({
el: '#app',
data: {
},
components: {
App
}
})
</script>
</body>
</html>