Vue 组件间有5种常见的数据共享方式:
1:props & $emit
2:依赖注入(provide,inject )
3:处理边界($root,$parent,$refs)
4:eventbus
5:vuex
下面详细介绍处理边界方式的数据传递:
处理边界
优点:当想要根组件的数据可以直接用 $root 获取、想要父组件的数据可以直接用 $parent 获取、想要子组件的数据可以直接用 $refs 获取,使用处理边界会比普通的传值更加方便
缺点:当变更了父组件数据的时候,很难找出变更是谁发起的。
$root :访问根实例
$parent:访问父组件的实例
$refs:访问子组件的实例
$root
// Vue 根实例
new Vue({
data: {
foo: 1
},
computed: {
bar: function () { /* ... */ }
},
methods: {
baz: function () { /* ... */ }
}
})
所有的子组件都可以将这个实例作为一个共享数据 来访问或使用。
// 获取根组件的数据
this.$root.foo
// 写入根组件的数据
this.$root.foo = 2
// 访问根组件的计算属性
this.$root.bar
// 调用根组件的方法
this.$root.baz()
$parent
和 $root 类似,$parent 属性可以用来从一个子组件访问父组件的实例。它提供了一种机会,可以在后期随时触达父级组件,以替代将数据以 prop 的方式传入子组件的方式。
<div id="app">
<compa></compa>
</div>
<script>
//子组件
const compb = {
//$parent.title父组件的title
template: '<h2>compb--{{$parent.title}}</h2>',
data() {
return {
title: 'from son title'
}
},
mounted() {
//this.$parent.*** 父组件的数据和方法
console.log(this.$parent.title)
console.log(this.$parent.start())
}
}
//父组件
const compa = {
template: `
<div>
<h1>
compa
</h1>
<compb ref="refCompb" ></compb>
</div>`,
data() {
return {
title: "from parent title"
}
},
methods: {
start() {
console.log('parent start ...')
}
},
components: {
compb
}
}
var vm = new Vue({
el: "#app",
components: {
compa
},
});
</script>
结果:
$refs
尽管存在 prop 和事件,有的时候你仍可能需要在 JavaScript 里直接访问一个子组件。为了达到这个目的,你可以通过 ref 这个 attribute 为子组件赋予一个 ID 引用。例如:
//子组件
const compb = {
template: '<h2>compb</h2>',
data() {
return {
title: 'from compb title'
}
}
}
//父组件
const compa = {
template: `
<div>
<compb ref="refCompb" ></compb>
</div>
`,
components: {
compb
},
mounted() {
console.log(this.$refs.refCompb.title);
}
}
结果:
调试面板结果:
参考文档:Vue教程