一、父组件数据流向自组件
<script>
// 需求: 父组件将数据传递给子组件
// 父组件: Vue实例
// 子组件: hello组件
// 通过属性传递的方式,来实现父子组件的通讯
// 1 在组件中通过 props 配置项,来说明该组件能够接受什么样的数据
// 2 在使用组件的时候,通过 属性 的方式,来给组件传递数据
// 注意:props是只读属性!!!无法修改
Vue.component('hello', {
template: `
<div>
<h1>这是子组件:hello</h1>
<p>子组件使用父组件中的数据msg: {{ parentmsg }} , {{ test }}</p>
</div>
`,
created() {
console.log('接收到属性:', this.parentmsg)
// 如果直接修改 props 的值,会报错!!!
// this.parentmsg = '修改了值'
},
// 通过该配置执行组件能够接受的数据
// props 的使用跟 data 中的数据一样
props: ['parentmsg', 'test']
})
const vm = new Vue({
el: '#app',
data: {
msg: '实例数据'
}
})
</script>
二、子组件数据流向父组件 ---完整案例
<!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">
<h1>父组件接受到子组件传递过来的数据:{{ msg }}</h1>
<!-- 渲染组件 -->
<!-- 2 将父组件中准备好的方法作为自定义事件传递给子组件 -->
<child @fn="fn"></child>
</div>
<script src="./vue.js"></script>
<script>
Vue.component('child', {
template: `
<div>
<input v-model="txt" />
<button @click="send">传递数据给父组件</button>
</div>
`,
data() {
return {
txt: ''
}
},
methods: {
send() {
// 3 子组件触发传递过来的自定义事件 fn
this.$emit('fn', this.txt)
}
}
})
const vm = new Vue({
el: '#app',
data: {
msg: ''
},
methods: {
// 1 父组件提供一个方法
fn(arg) {
console.log('接受到子组件数据为:', arg)
this.msg = arg
}
}
})
</script>
</body>
</html>
三、兄弟组件数据流
<!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">
<jack></jack>
<rose></rose>
</div>
<script src="./vue.js"></script>
<script>
// 非父子组件(兄弟组件):
// 场景:jack组件要对rose组件说: 'i love u'
// 发送数据的组件:jack,触发事件,传递数据
// 接受数据的组件:rose,注册事件
// 思路:
// 1 rose组件要接受数据,因此,rose组件注册事件 bus.$on('love', () => {})
// 2 jack组件要传递数据,因此,jack组件触发事件 bus.$emit('love', '要传递的数据')
// 创建一个bus
// bus 实际上就是一个空的vue实例
// 注意: 注册事件和触发事件需要使用同一个bus
const bus = new Vue()
// jack组件
Vue.component('jack', {
template: `
<div>
<h2>Jack组件:</h2>
<button @click="sendLove">告诉rose:i love u</button>
</div>
`,
methods: {
sendLove() {
// jack触发事件,将数据作为参数传递
bus.$emit('love', 'i love u')
}
}
})
// rose组件
Vue.component('rose', {
template: `
<div>
<h2>Rose组件:</h2>
<p>我是rose,jack你说啥??? {{ msg }}</p>
</div>
`,
created() {
// 进入页面就注册事件
bus.$on('love', (arg) => {
this.msg = arg
})
},
data() {
return {
msg: ''
}
}
})
const vm = new Vue({
el: '#app',
data: {
}
})
</script>
</body>
</html>
网友评论