我有一个叫做Profile.vue的页面,它的结构是这样的,
<style>
</style>
<template>
<component-1></component-1>
<component-2></component-3>
<component-3></component-3>
</template>
<script>
import component1 from '...../..'
import component2 from '...../..'
import component3 from '...../..'
export default {
name: 'profile',
data(){
return{
pagename: 'Profile',
mydata: 'This is my data'
}
}
}
</script>我如何使mydata中的数据对我导入的所有组件可用,即,我如何传递对所有组件可用的数据?
发布于 2017-08-12 10:06:53
您可以使用props。
<component-1 v-bind:message="mydata"></component-1>然后在你的子组件中(直接从文档中):
Vue.component('component-1', {
// declare the props
props: ['message'],
// just like data, the prop can be used inside templates
// and is also made available in the vm as this.message
template: '<span>{{ message }}</span>'
})发布于 2021-01-29 16:26:52
您可以使用$parent (或$root)访问变量,而不是使用props (这可能意味着您必须多次传递这些props )
Vue.component('component-1', {
computed: {
message: function(){
// this is how to access the variable inside the component code
return this.$parent.message;
},
},
// and because of using computed, access it inside the template
template: '<span>{{ message }}</span>'
})发布于 2017-08-12 10:08:47
你只是导入了一些非继承的组件,所以你不能像那样共享数据。将组件添加到父组件的组件字段中,如下所示:https://vuejs.org/v2/guide/components.html#Local-Registration,然后在子组件中可以使用.$ parent。在您的示例中使用this.$parent.mydata
https://stackoverflow.com/questions/45645204
复制相似问题