父级组件向子级组件传值:
子级组件向父级组件传值:
<!-- App.vue -->
<template>
<div>
<h1>hello vnsief</h1>
<h2>{{ChildCodata}}</h2>
<ChildCo :msg="message" @myevent="changeData"></ChildCo>
</div>
</template>
<script>
// 引入组件
import ChildCo from './components/ChildCo.vue'
export default {
name: 'App',
// 注册组件
components: {
ChildCo
},
// 数据保存在return的对象中
data:function(){
return{
message:"hello rst try",
isLogin:false,
fruits:["香蕉","苹果","鸭梨"],
ChildCodata:""
}
},
// 方法
methods:{
sayHi:function(){
alert("hi")
},
changeData:function(childdata){
console.log(childdata);
this.ChildCodata = childdata;
}
}
}
</script>
<!-- ChildCo.vue -->
<template>
<div>
<h1>{{msg}}</h1>
<button @click="sendData">传递数据</button>
</div>
</template>
<script>
export default{
props:['msg'],
data:function(){
return {
childdata:"子级组件的数据"
}
},
methods:{
sendData:function(){
// 触发父级的自定义事件myevent
this.$emit("myevent",this.childdata)
}
}
}
</script>
此外还有同级组件传值,计算属性computed,侦听器属性watch等,了解即可。