Still new to Vue.js, but very much enjoying to learn about it. Before I get to using Axios and Vuex store I'd like to understand how can I send some test data from a separate file to my component? Hope someone can help.
If I do this within my component it works:
<script>
export default {
data () {
return {
logItems: [
{ log1d: 1, logDetail: 'This is some log detail for log 1', logType: 'general', createdBy: 'name', CreatedAt: 'date' },
{ log1d: 2, logDetail: 'This is some log detail for log 2', logType: 'general', createdBy: 'name2', CreatedAt: 'date2' },
{ log1d: 3, logDetail: 'This is some log detail for log 3', logType: 'general', createdBy: 'name3', CreatedAt: 'date3' },
{ log1d: 4, logDetail: 'This is some log detail for log 4', logType: 'general', createdBy: 'name4', CreatedAt: 'date4' }
]
}
}
}
But I assumed I could import it as follows from an external file:
import logs from '~/components/testdata.vue'
export default {
data () {
return {
logitems: logs
}
}
}
And in my testdate.vue file I have:
<script>
export default {
data () {
return {
// Dummy Test Data
logs: [
{ log1d: 1, logDetail: 'This is some log detail for log 1', logType: 'general', createdBy: 'name', CreatedAt: 'date' },
{ log1d: 2, logDetail: 'This is some log detail for log 2', logType: 'general', createdBy: 'name2', CreatedAt: 'date2' },
{ log1d: 3, logDetail: 'This is some log detail for log 3', logType: 'general', createdBy: 'name3', CreatedAt: 'date3' },
{ log1d: 4, logDetail: 'This is some log detail for log 4', logType: 'general', createdBy: 'name4', CreatedAt: 'date4' }
]
}
return logs
}
}
Is anyone able to tell me what am I doing wrong and why putting my data into a separate file doesn't work, please?
Many thanks.
When you import any file, webpack uses an appropriate
loader
(specified in yourwebpack.config.js
) to build the file. In case it is a.vue
file, it usesvue-loader
to build the file and return a Vue component. You need an Array containing your data, not a vue component. You can import simple.js
and.json
files for this.Instead of importing a
.vue
file. you can just import.json
or.js
file.data.js
component.vue
Explainations
If you are using Vue template files, you can use the script tag src's attribute just like you would normally do with any other scripts in your HTML page.
Since Webpack is doing some special stuff when you import a Vue template file, for instance
example.vue
, you have to explode your configuration to extract the JavaScript part, that should not be compiled by thevue-loader
.Example
index.vue
index.js
something.js
Online Example
External Resources
See What-About-Separation-of-Concerns
I personally do it in the following way: