vue父子,子父组件传值 ,props $emit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="example-1">
<father></father>
</div>
<template id="father">
<div id="">
<div> {{msg}}</div>
<son :test='infoFather' @testson='testsonHander'></son>
</div>
</template>
<template id="son">
<div id="">
{{msg}}
{{test}}
<!-- test 接受父组件的数据显示在这里 -->
<button @click='clickHander'>点击触发son</button>
<!-- 子组件先定义个单击事件 用来触发this.$emit这个方法 -->
</div>
</template>
<script type="text/javascript">
Vue.component('father', {
template: '#father',
data(){
return{
msg:'father',
infoFather:'how are you'
}
},
methods:{
testsonHander(val1,val2){
console.log(val1,val2)
}
}
})
Vue.component('son', {
template: '#son',
data(){
return{
msg:'son',
infoSon:'i am son'
}
},
methods:{
clickHander(){
this.$emit('testson','你好',this.infoSon)
},
},
props:['test'],
})
new Vue({
el: '#example-1',
data: {
},
})
</script>
</body>
</html>
$parent, $children, $refs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdn.bootcss.com/vue-router/3.1.3/vue-router.js"></script>
</head>
<body>
<div id="app">
<div>{{msg}}</div>
<div>
<table_o ref="childmsg"></table_o>
</div>
</div>
<template id="table">
<div>
<div>{{msg}}</div>
</div>
</template>
<script>
var table_o = {
template:"#table",
data(){
return{
msg:"你好啊!世界!"
}
},
mounted(){
console.log(this.$parent)
console.log(this.$parent.msg)
}
}
var vm = new Vue({
el:"#app",
components:{
table_o
},
data:{
msg:"hello world",
},
mounted(){
console.log(this.$children)
console.log(this.$children[0].msg)
console.log(this.$refs.childmsg.msg)
}
})
</script>
</body>
</html>
事件总线
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdn.bootcss.com/vue-router/3.1.3/vue-router.js"></script>
</head>
<body>
<div id="app">
{{msg}}
<zujian1 ></zujian1>
<zujian2 ></zujian2>
</div>
<template id="zujian1">
<div>
{{msg}}
<button type="button" @click="clickhandel">emit</button>
</div>
</template>
<template id="zujian2">
<div>
{{msg}}---{{str1}}
</div>
</template>
<script>
var zujian1={
template:"#zujian1",
data(){
return{
msg:"我是组件1",
info:"i love you"
}
},
methods:{
clickhandel(){
bus.$emit('busdel',this.info)
}
}
}
var zujian2={
template:"#zujian2",
data(){
return{
msg:"我是组件2",
str1:""
}
},
created(){
bus.$on('busdel',(val)=>{
console.log(val)
this.str1 = val
})
},
}
var bus = new Vue()
var vm = new Vue({
el:"#app",
components:{
zujian1,
zujian2
},
data:{
msg:"hello world",
},
})
</script>
</body>
</html>
vuex