Vue - Passing same data from one component to many component - javascript

I have the following code.
main.js
new Vue({
el: '#app',
template: '<App/>',
components: { App }
})
App.vue
<template>
<div id="app">
// this does not pass the data to the component
<basics :resume="resume"></basics>
<education :resume="resume"></education>
// this gets the value from the json file
{{resumeData.name}}
{{resumeData.education}}
</div>
</template>
<script>
import Basics from './components/Basics.vue'
import Education from './components/Education.vue'
import Resume from '../resume.json'
export default {
name: 'app',
data() {
return {
resumeData: Resume
}
},
components: {
Basics,
Education
}
}
</script>
/components/Basics.vue
<template>
<div>
<p>Basics</p>
// this does not get the value from the json file
{{resumeData.name}}
</div>
</template>
/components/Education.vue
<template>
<div>
<p>Education</p>
{{resumeData.education}}
</div>
</template>
How do I pass the data from one component to another such that all the different vue components is reading data from the same json file without inserting the code import Resume from '../resume.json in each component?
I hope you understand my question.

A more common / standard way is just use props. Or you have to import the json in all your components.
If you have many components and really don't want to pass the same prop several times, there is tricky solution: inject the data to the Vue.prototype globally:
Vue.prototype.$resume = {
name: 'foo',
education: 'bar',
...
}
with this, all your components can access it via this.$resume. But use it wisely.
If you have other similar cases, you probably should go for vuex.

In vue.js course you can solve this in 3 different ways.
Use props to pass data in Basics and Education
Vuex
Event box

Related

how to properly pass prop from laravel 8 blade to vue 3 component

I'm trying to get the value of user prop as in the blade file when the App component is mounted but I get undefined in the console. I was wondering if something changed in Vue 3 because it worked in Vue 2.
How can I get the value of the user prop?
laravel.blade file
#extends('layouts.app')
#section('content')
<App
#if(auth()->check())
:user="1"
#endif>
</App>
#endsection
App.vue
<template>
<div> {{user}} </div>
</template>
<script>
export default {
name: 'App',
props: [ 'user'],
mounted(){
console.log(this.user)
}
}
</script>
app.js
import { createApp } from 'vue';
import App from './components/App'
import router from './router';
require('./bootstrap');
const app = createApp(App)
app.use(router).mount("#app")
From the migration docs:
The propsData option has been removed. If you need to pass props to the root component instance during its creation, you should use the second argument of createApp
const app = createApp(
{
props: ['username'],
template: '<div>{{ username }}</div>'
},
{ username: 'Evan' }
)
It's not as convenient as the Vue 2 way, and I haven't found a good work-around of sending data from your Laravel controller directly to your Vue component. Best bet may be to get the info by querying your API in the created() method in Vue.

component structure in Vue

First: I'm using Vue since last night, so the answer is probably obvious.
I find components with that layout:
<template>
<Slider v-model="value"/>
</template>
<script>
import Slider from '#vueform/slider'
export default {
components: { Slider },
}
</script>
<style src="#vueform/slider/themes/default.css" />
but at the same time, I also find components that are structured like a JS object:
app.component('button-counter', {
data() {
return {
count: 0
}
},
template: `
<button #click="count++">
You clicked me {{ count }} times.
</button>`
})
Is there a practical difference? is one preferred? is one more Vue2 vs. Vue3?
The following syntax called SFC single file component :
<template>
...
</template>
<script>
...
</script>
<style src="#vueform/slider/themes/default.css" />
which requires a bundler like webpack or vue cli to be transpiled, the second syntax (your example is based on vue 3) is used to define global component which could work if you're using Vue via CDN,
the first syntax is preferred when you setup a medium/large projects.

How to pass props to Vue from another js module?

Is it possible to pass props from any js module to vue?
Props are passing fine between components for me, but not from the actual Vue app itself:
main.js
import Vue from 'vue'
import App from './App.vue'
var myVue = new Vue({ export to other files
el: '#entry',
components: {App},
render: h => h(App),
data: function(){
return{
testSuccess:'this test was successful!'
}
},
})
window.myVue = myVue // we use window.myVue because if we can export to window, we can export to other js modules.
App.vue
<template>
<div ref="app">
{{ testSuccess ? testSuccess : 'prop not imported!' }}
</div>
</template>
<script>
export default = {
name: "app",
props: ["testSuccess"]
}
</script>
index.html
<div id="entry" >
<app :testSuccess="testSuccess"></app>
</div>
<script src="/dist/build.js"></script>
What am I missing?
I understand how to do this with components.
I want to be able to export the Vue module into other js modules and pass meaningful information to it.
This is the render function for your root Vue instance:
render: h => h(App)
You aren't passing any props to h, so the App will be created without props.
The template inside #entry will be ignored because you're providing an explicit render function.
So either:
Remove the render function from the root Vue instance. Note that the reason most examples use a render function is so that they can use the runtime-only build of Vue, which can't compile templates.
Remove the template from inside #entry and pass the props to App within the render function.
The latter would look like this:
render (h) {
return h(App, { props: { testSuccess: this.testSuccess } })
}
Note this can't use an arrow function because it requires access to this.
Once you're passing the props correctly you should be able to update the value using myVue.testSuccess = '...' no problem.
As you have discovered, you cannot pass props to your $root Vue app. However, you can modify the properties of the Vue instance and Vue will react to those changes.
In your example above, you could write anywhere (including the console):
window.myApp.testSuccess= "I've been changed!";
and the HTML should update.
However, the way you have written your components above mean that the testSuccess property is not being passed into the App.vue component. Instead of making your App.vue a component of the root Vue instance, create them like this:
index.html
<div id="app" >
</div>
<script src="/dist/build.js"></script>
main.js
import Vue from 'vue'
import App from './App.vue'
var myVue = new Vue({ // export to other files
el: '#app',
...App,
})
window.myVue = myVue // we use window.myVue because if we can export to window, we can export to other js modules.
App.vue
<template>
<div>
{{ testSuccess || 'testSuccess is blank!' }}
</div>
</template>
<script>
export default {
data: { // doesn't need to be a function in the root Vue instance
testSuccess: "this is the default text",
...
}
</script>
AN EVEN BETTER WAY
Despite all the above, an even better way is to use proper state management. By placing all your shared state into a dedicated state object (or VueX), any module which has access to the state object can manipulate the state.
Have a read of https://v2.vuejs.org/v2/guide/state-management.html

Is there a way to use RequireJS when importing VueJS components?

I have a project which uses RequireJS and Vue components. I am trying to modularise the Vue components into smaller parts and I want to be able to export smaller vue components so that they can be used by a bigger one. This is simple with standard vue:
import SomeComponent from './SomeComponent.vue'
new Vue({
el: '#app',
...
components: { SomeComponent },
...
}
but how would this be done with requireJS?
You can use require to import your *.vue components like this:
new Vue({
el: '#app',
...
components: {
'some-component': require('../path/to/components/SomeComponent.vue').default,
...
},
...
});
Your *.vue files should be structured like this:
<template>
<!-- Component HTML -->
</template>
<script>
export default {
name: 'some-component',
...
}
</script>
<style>
/* Component Styles */
</style>
As an alternative, you can use require to register you components globally (see api docs):
Vue.component('some-component', require('../path/to/components/SomeComponent.vue').default);
new Vue({
el: '#app',
... // no need to declare `SomeComponent` here
});
This is a good option if you have several components that will all make use of SomeComponent.
I'm not exactly certain what you are asking, but if you are just trying to modularize, you can do this with import. The way to do this is by importing components into components.
If you have a pagination component that is being imported to your app, you can import a smaller component (a sub-component) into pagination component. You can go as small as you want this way and have sub-sub-sub-components. The syntax for importing components into components is identical to importing components into a new vue page.
Unless I'm missing something, there's no reason to try and use require. Vue already gives you everything you need with the ability to import components. That's the proper way to modularize and keep your code DRY in Vue.

Using Vueify for components with the runtime-only build in Vue.js

I've been working on porting a vue.js component from vue 1.0 to Vue 2.0 using Vueify. In the Starter resources it states:
When you use vue-loader or vueify to import *.vue files, their parts are automatically compiled into render functions. It is therefore recommended to use the runtime-only build with *.vue files.
However, this does not appear to be the case. If I have a simple component like:
<template>
<div>
{{ msg }}
</div>
</template>
<script type="text/javascript">
export default {
props: {
msg: {
default: "Child Message"
}
}
}
</script>
And in my main.js file I do:
import Vue from 'vue'
import MyComponent from './my-component.vue';
Vue.component('my-component', MyComponent);
new Vue({
el: '#app',
render: function(createElement) {
return createElement(MyComponent)
}
});
Then compile with Gulp using:
browserify('./main.js')
.transform(vueify)
.bundle()
.pipe(fs.createWriteStream("bundle.js"))
I cannot do anything at all with the component except get it to render. In fact, it will actually render the component as soon as it finds the div with the id "app":
<div id="app">
<!-- my-component renders even though I didn't ask it to -->
</div>
And any props added to the component are not received, so:
<div id="app">
<!--
Message displays as default "Child Message" rather than "Parent Message". The prop wasn't passed
-->
<my-component msg="Parent Message"></my-component>
</div>
Similarly, if I add data to main.js, it's not accessible from the web page:
import Vue from 'vue'
import MyComponent from './my-component.vue';
Vue.component('my-component', MyComponent);
new Vue({
el: '#app',
render: function(createElement) {
return createElement(MyComponent)
},
data() {
return {
msg: "Parent Message"
}
}
});
in HTML:
<div id="app">
{{ msg }} // This will not print
</div>
And anything inside "#app" doesn't render at all (remember "my-component" is rendered even if I don't add it):
<div id="app">
<!-- This doesn't render-->
<strong>A component </strong>
<my-component></my-component>
</div>
So it looks to me like you can render a component, without any control over it, and you cant do anything further with the view model, so is it really the case that I should be using the runtime-only build as suggested?
In the end I've used the standalone build using aliasify and everything works fine, but I'd really like to know what it is I am missing when using vueify with the runtime build. Surely the behavior I'm describing isn't what is supposed to happen, so I can only assume I have misunderstood something somewhere.
Doing some tests the problem is in your default render function:
render: function(createElement) {
return createElement(MyComponent)
}
It's overriding the main Vue file's render function and creating a base MyComponent inserting it into the body.
When I removed the render function the prop fired.
jsFiddle Try that, just uncomment the render function to see what I mean.
The render function is meant to replace html templating by allowing you to have more control and utilize other template options.

Categories

Resources