Vue js dynamically loaded component name from ajax - javascript

I am new in vuejs . I want to load component from ajax response.
<div id="app"></div>
export default(){
created: function(){
const url = "xyz.json";
this.$http.get(url).then(response => {
this.resp = response.body;
var comp = this.resp.components;
}
}
}
Here is my JSON response
{
components: "Hello.vue",
}
I want to draw dynamically components by using json data
Update:
My Purpose is to draw a vuejs component in response of server side data. In server side data, I will tell which component will be loaded for this particular action. For example, I want to render particular view in response of drop-down value. If value is 1 , then server will tell load A component, if value is 2, then server will tell load B component.

Related

What is optimal data flow between PHP backend and Vue frontend

I am wondering, what would be the best setup of data flow from PHP (database) to fronted Javascript rendering, lets say VueJS.
My first idea is, that will provide data attribute with JSON data to HTML element - div, which Vue instance will be mounted on.
I dont want to create REST API and load data via AJAX HTTP requests from Vue.
# PHP part
echo '<div id="myId" data-my-data="{h1:\"My heading\"}"></div>';
// Javascript part
import Vue from 'vue/dist/vue.js';
import App from './MyApp.vue';
const el = document.querySelector('#myId');
new Vue({
el,
render: h => h(App, {
props: {
myData: JSON.parse(el.dataset.myData),
},
}),
});
What do you think, is it ok or is there any other option except REST?
Update:
Main purpose is that my App will handle complex - multi-step Forms with some complex fields, which I would like to create as reusable components.
App will validate forms via AJAX (to prevent re-rendering page), on success redirect to success page.
My infrastructure would be, that PHP will prepare data, render main layout with assets (JS + CSS) and DIV with data atributes for Vue App.

Is it possible to server side render only one component?

I have a react app which is rendered on the client side. Now I have a component which I want to render on the server side. I am doing this because the component will construct its layout from a json and I do not want to parse the json once on the server and again on the client to render the component.
Right now, I am doing renderToString(<Component/>) and sending it to the client. The client then does ReactDOM.hydrate(component,document.getElementById('someDivId')). But it only renders the component as a string. It is not rendering it as an element. The container on which I am trying to render the component is a client-side rendered react app.
Example code as below
server.js
app.get('/component/:id',(req,res,next)=>{
const markup = renderToString(
<div>Hello</div>
)
let jsonModel = {
markup
}
return res.json(jsonModel);
})
client.js
getComponent(id).then(data => {
ReactDOM.hydrate(data.markup, document.getElementById('someDivId'));
});
Is it possible to render only one component on the server side? Or do I have to render the whole app on the server side?

How to send the data using react js to another page?

I have index.html. In that I have form which accepts some data.After clicking on submit button, I want to send the all data to the process.php file in ajax format using react js. Thanks in Advance.
Correct way :
There is no AJAX functionality in the Reactjs. Basically react is just a view layer. For use of Network layer and Data layer you have to use some other configuration with React . Best will be Reactjs + Flux like facebook.
I like fluxxor for fluxx + react combination. fluxxor provides actions . By using those action you can call some external API.
Or Hack :
var Form = React.createClass({
submit:function(e){
e.preventDefault();
// make ajax call .
},
render: function() {
return (
<form onsubmit = {this.submit} > </form>
);
}
});

Rendering View with Data from Zend Controller for Angular JS

I am in need of this unique requirement where my backend is PHP with Zend Framework in MVC pattern and frontend is Angular JS, I need to pass data from the backend to the Angular JS controller and render the view at the same time.
As far as I know if the backend class inherits Zend_Controller_Action, it returns only View and not data and if the backend class inherits Zend_Rest_Controller, it returns only data and not view.
Is this right and is there a way to render the view as well as return the data without using the $this->view->data concept.
For returning JSON data all you need is the JSON Action Helper
public function someAction() {
// create an array with your data
$data = array();
// to add some view data
$data['html'] = $this->view->render('/path/to/script/script-name.phtml');
// essentially you can load and render any script and I am
// not 100% sure but without a path it would render the default
// action script in view/scripts/controller-name/action-name.phtml
// Send the JSON response. Both methods do the same
$this->_helper->json($data);
$this->_helper->json->sendJson($data);
// NOTE both methods terminate and return the data
// i.e. the follow should not been seen
echo "This should not be seen!";
}
This helper will set the appropriate headers and simply return a JSON object. If you have some error handling in your action and need to return codes other than 200OK you can also fetch the response object $this->getResponse() and set those values.
There are other variations where you would set layout to noRender and contexts but that's all handled already by the JSON helper.

Render React JS server side using .net

I did the comments tutorial on http://reactjs.net/getting-started/tutorial.html and got it to render server side using .net mvc.
I have an existing mvc app where I rewrote a page in react. I'm trying to render it server side using .net but I get an error when it tries to render server side.
Exception Details: React.Exceptions.ReactServerRenderingException: Error while rendering "TopicAnswers" to "react1": TypeError: undefined is not a function
at React.createClass.render (Script Document [8]:80:39) -> var answerNodes = this.props.data.map(function(answer){
at ReactCompositeComponentMixin._renderValidatedComponentWithoutOwnerOrContext (Script Document [2]:7395:34)
Here's the code:
In my MVC view:
#Html.React("TopicAnswers", new
{
initialAnswers = Model,
url = Url.Action("TopicAnswers", new { id = ViewBag.TopicID }),
})
My TopicAnswers.jsx file:
var TopicAnswers = React.createClass({
getInitialState: function(){
alert('inside getInitialState: ' + this.props.initialAnswers);
return {answers: this.props.initialAnswers};
}
My ReactConfig.cs file:
ReactSiteConfiguration.Configuration
.AddScript("~/Scripts/internal/eusVote/TopicAnswers.jsx");
QUESTION: Why is it having a problem rendering the react file server side?
I got this error message trying to render React jsx file server side using .net:
"React.Exceptions.ReactServerRenderingException: Error while rendering "TopicAnswers" to "react1": TypeError: undefined is not a function"
My problem was that in the JSX file, I still had ComponentWillMount which called the loadAnswersFromServer. This is what you need if you are rendering client side. But once you adjust your code to render server side, you need to comment out/remove the ComponentWillMount so that it doesn't try to run the loadAnswersFromServer function on the server side.
With MVC, the data should be passed from the controller to the view and referenced in the #Html.Render("Comment", new { initialData = Model }) for the initial load.
Also, don't forget to comment out/remove the React.render( ... ) line from the JSX file.
alert is available only in browser window context. When rendering it on a server you can not call any functions that are browser related. If you are calling them, then you need to shim them so they are not failing on a server.

Categories