父组件获取子组件的属性,方法,元素
<div id="parent">
<user-profile ref="profile"></user-profile>
</div>
var parent = new Vue({ el: '#parent' })
// 访问子组件
var child = parent.$refs.profile
子组件获取父组件的数据,方法
1:子组件使用props从父组件获取数据
<child message="hello!"></child>
Vue.component('child', {
// 声明 props
props: ['message'],
// 就像 data 一样,prop 可以用在模板内
// 同样也可以在 vm 实例中像“this.message”这样使用
template: '<span>{{ message }}</span>'
})
双向绑定(.sync)
只用通过 this.$emit(‘update:activeId1’,1) 这种方式才能进行数据双向改变;
2:子组件通过v-on绑定自定义事件到父组件的方法,再通过$emit触发这个自定义事件;进而调用父组件事件
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
Vue.component('button-counter', {
template: '<button v-on:click="incrementCounter">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
incrementCounter: function () {
this.counter += 1
this.$emit('increment')
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})
非父子组件通信(路由跳转以后不实用)
网说的太简单了,新手看完估计还是一脸懵逼。还有这个空的 Vue 实例放到哪里合适也值得商榷。这篇文章的目的就是用一个简单的例子让你明白如何用 Bus 来进行通信:
假设 bb 组件里面有个按钮,点击按钮,把 123 传递给 aa 组件
// 根组件(this.$root)
new Vue({
el: '#app',
render: h => h(App),
data: {
Bus: new Vue()
}
})
bb组件被触发事件
<button @click="submit">提交<button>
methods: {
submit() {
// 事件名字自定义,用不同的名字区别事件
this.$root.Bus.$emit('eventName', 123)
}
}
aa组件内调用事件接受
{{value7}}
data() {
return {
value7:'旧的',
};
},
// 当前实例创建完成可以就监听这个事件
created(){
this.$root.Bus.$on('eventName', value => {
this.print(value)
})
},
// 或者在updata中监听这个事件
updated: function updated() {
//do something after updating vue instance
this.$root.Bus.$on('eventName', value => { this.print(value) })
},
methods: {
print(value) {
this.value7=value
}
},
// 在组件销毁时别忘了解除事件绑定
beforeDestroy() {
this.$root.Bus.$off('eventName')
},
路由跳转不改变的原因是eventName事件没有改变;eventName是事件而不是属性;