Let's say I have some data in a Vue ponent (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 '@/ponents/Data'
What other steps do I need to take?
Let's say I have some data in a Vue ponent (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 '@/ponents/Data'
What other steps do I need to take?
Share Improve this question edited Apr 15, 2020 at 8:21 Ragnar Lothbrok asked Apr 15, 2020 at 8:02 Ragnar LothbrokRagnar Lothbrok 1,1452 gold badges19 silver badges37 bronze badges 2- you should take a look about mixins vuejs/v2/guide/mixins.html – Ilijanovic Commented Apr 15, 2020 at 8:04
-
like mentioned above
mixins
is one option (according to your situation) because global mixins is big NO NO. Another way is you can send the data1 as prop and watch it for changes... OR you can use VUEX. – yvl Commented Apr 15, 2020 at 8:37
2 Answers
Reset to default 2You may have more than one ponent Data
and then it doesn't bees clear which one you want to share.
If you have only one ponent 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 '@/ponents/Data'
But this is kindof hacky, you should use a store live vuex
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/v2/guide/ponents-props.html
"Hello world example"
Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.ponent('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./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/v2/api/#vm-on