一. 父组件向子组件传值
1. 使用props建立数据通道的渠道
// 这是父组件
<div id="app">
// 这是子组件
<child message="hello" ></child>
</div>
2 . 在子组件中通过props传递过来的数据
Vue,component('child',{
props:['message']
})
二. 子组件向父组件传值
1. 子组件中需要一个点击事件触发一个自定义事件
Vue.component('child',{
methods:{
handleClick(){
// 在相应该点击事件的函数使用$emit来触发一个自定义事件,并传递一个参数
this.$emit('parentClick',123)
}
},
template:`
<div>
<h1>这是子组件</h1>
<button @click="handleClick" >
发送给父组件
</button>
</div>
`
})
2.在父组件中的子标签监听该自定义事件得到传递的值
Vue.component('parent', {
data() {
return {
msg: '我是子组件'
}
},
methods: {
receiveMsg(value) {
console.log(value)
this.msg = value
}
},
template:'
<div>
<h1>这是子组件</h1>
<p>接收子组件传过来的值{{msg}}</p>
<child @parentClick='receiveMsg'></child>
</div>
'
})
三. 非父子组件传值
有时候两个组件也需要传值(非父子关系),所以我们需要一个公共的vue来进行传递值和获取值
1 . 创建一个空的vue
// 创建一个空的公共的vue对象
var bus = new Vue();
2 . 在组件1中,定义$emit来发送数据
bus.$emit('test','数据')
3 . 在组件2中使用$on来接收传递的数据
bus.$on('test', function(num) {
this.msg= num;
//事件的解绑问题
bus.$off("test")
})
当然非父子传值的方法不只有一种我们也可以使用 localstorage 来传值和取值
// 在第一个组件中 setItem 设置值
localstorage.setItem('test','数据')
// 在第二个组件中 getItem 获取值
localStorage.getItem("test");