Reputation: 1135
Let's say I have some data in a Vue component (we'll call it Data.vue) like this:
<script>
export default {
data(){
return{
data1: {some data}
}
}
}
</script>
I want to use that data on another page (Main.vue) in a method.
<script>
export default {
methods: {
someMethod: function(){
console.log(this.data1)
}
}
}
</script>
How would I go about doing this?
I did try importing it the data to "Main.vue" like this:
import { data1 } from '@/components/Data'
What other steps do I need to take?
Upvotes: 2
Views: 14553
Reputation: 7741
Your Q is too general because It depends (From child to parent? global data? read-only data? and so on).
One basic way is by props. Example: Pass data (array/object/string and so on) From parent-to-child https://v2.vuejs.org/v2/guide/components-props.html
"Hello world example"
Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('child', {
// camelCase in JavaScript
props: ['message_from_parent'],
template: '<h3>{{ message_from_parent }}</h3>',
created: function () {
console.log(this.message_from_parent)
}
})
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<child v-bind:message_from_parent="message"></child>
</div>
Or the opposite (From child to parent) by $emit: https://v2.vuejs.org/v2/api/#vm-on
Upvotes: 2
Reputation: 14171
You may have more than one component Data
and then it doesn't becomes clear which one you want to share.
If you have only one component then you can just export data
<script>
const data1 = {some data}
export { data1 }
export default {
data () {
return {
data1
}
}
}
</script>
and then your import should work.
import { data1 } from '@/components/Data'
But this is kindof hacky, you should use a store live vuex
Upvotes: 2