Vue.component(‘indexmain‘,{
template:‘<div><h1 @click="sendMsg">这是个按钮,可以改变父组件内容</h1></div>‘,
data:function(){
return {
msg:‘indexmain‘
}
},
methods:{
sendMsg:function(){
//自定义触发事件,this.$emit(‘自定事件名称‘,‘事件的内容‘)
this.$emit(‘send‘,this.msg)
}
}
})
Vue.component(‘indexfooter‘,{
template:`<div><h1 @click="changeMsg">这是{{msg}}</h1></div>`,
data:function(){
return {
msg:‘indexfooter‘
}
},
methods:{
changeMsg:function(){
this.msg = ‘更改内容‘
}
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<headnav user=‘xx‘></headnav>
<indexmain @send=‘changeChild‘></indexmain>
<indexfooter></indexfooter>
<headnav :user=‘username‘></headnav>
<h1>{{childContent}}</h1>
</div>
<script src="js/indexComponent.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
Vue.component(‘headnav‘,{
template:‘<div><h1>欢迎{{user}}</h1></div>‘,
props:[‘user‘],
data:function(){
return {
msg:‘headnav‘
}
}
})
import HelloWorld from ‘./components/HelloWorld.vue‘
var app = new Vue({
el:‘#app‘,
data:{
username:‘隔壁老王‘,
childContent:‘‘
},
methods:{
changeChild:function(value){
console.log(value)
this.childContent = value
}
}
})
// npm install -g cnpm --registry=https://registry.npm.taobao.org
//npm install -g @vue/cli
//组件:要想父组件传递数据给子组件,那么需要使用props
//如果想要子组件将数据传递给父父组件,那么需要使用自定义事件,$emit(事件名称,事件内容),进行触发,监听:@事件名称=‘要执行的函数’
</script>
</body>
</html>
原文:https://www.cnblogs.com/wwthuanyu/p/10554839.html