组件的通信

不推荐用事件中心,还是记下,准备一个事件中心 var bus = new Vue(),通过bus.$on准备一个函数,通过 bus.$emit 触发一个函数

如果是父组件要传值给儿子的儿子.就是一个A组件嵌套了B组件,B组价有嵌套了C组件
A组件要给C组件传值
就先传值给B组件.在B组件里面用 v-bind='$attrs' v-on='$listeners',向下传递属性和方法
在c组件里面就可以直接使用{{$attrs}}使用.如果是事件可以使用$emit('',参数),给A组件传值

Vue.component("a-component", {
data() {
return {
first: "我是最好看的,令人窒息的美貌",
}
},
template: `
<div>
我是A组件
<b-component :mm='first' v-on:yy='yyhandlers'></b-component>
</div>`,
methods: {
yyhandlers(v) {
console.log(v, "这是C组件给A组件传的值")
},
},
})

Vue.component("b-component", {
template: `
<div>
我是B组件
<c-component v-bind='$attrs' v-on='$listeners'></c-component>
</div>`,
})

Vue.component("c-component", {
template: `
<div>
我是C组件--{{$attrs}}--<button @click="$emit('yy','ccccccc')">小按钮 </button>
</div>`,
})

var vm = new Vue({
el: document.querySelector("#app"),
})

 

 



后代传值 provide inject
从root根组件里面开始传.
就从实例里面开始传.通过provide里面注册.

 

 

<script>
// 比如有一个A组件嵌套了B组件,B组价有嵌套了C组件
Vue.component("a-component", {
inject: ["jc"],
template: `
<div>
我是A组件--{{jc}}
<b-component></b-component>
</div>`,
})

Vue.component("b-component", {
inject: ["jc"],
template: `
<div>
我是B组件---{{jc}}
<c-component></c-component>
</div>`,
})

Vue.component("c-component", {
inject: ["jc"],
template: `
<div>
我是C组件--{{jc}}
</div>`,
})

var vm = new Vue({
el: document.querySelector("#app"),
data() {
return {
jc: 100000000000,
}
},
provide: {
jc: 100000000000,
},
})
</script>

 




通过this.$children[0].$children[0].属性 就可以拿到组件孩子的孩 子的属性
this.$parent.属性.拿到自己父亲的属性
this.$root.属性就拿到了根组件的属性
杀鸡焉用载牛刀,明明获取属性,确先获取了组件

 

最后一种$refs和$ref,和上面的很像,也是获取组件.最近的一种

<div id="app">
<a-component ref="myrefA"></a-component>
</div>
<script>
// 比如有一个A组件嵌套了B组件,B组价有嵌套了C组件
Vue.component("a-component", {
template: `
<div>
我是A组件--
</div>`,
})
var vm = new Vue({
el: document.querySelector("#app"),
mounted() {
console.log(this.$refs.myrefA) // 获取到了A组件
},
})
</script>


刚刚发现一种props传参.
跟路由传参很像,就是在路由规则里面,添加props:true.在组件里面就可以直接用props: ['id'],就可以直接用了.就不用$route.params.id

posted on 2020-05-06 15:52  危险*  阅读(150)  评论(0编辑  收藏  举报