My request for a second view it doesn't show anything - ruby-on-rails

I'm using ruby on rails as framework and vue.js to display de data and for the request to the API I'm using axios.
first I create project with:
rails new myapp --webpack=vue
that created one folder in rails:
app/javascript
└── packs
├── app.vue
└── hello_vue.js
app.vue:
<template>
<div id="app">
<ul v-for="result in results">
<li>{{result.name}}</li>
</ul>
<!-- <p>{{ results.name}}</p> -->
</div>
</template>
<script>
export default {
data: {
results: []
},
mounted(){
axios.get("xxxxx")
.then(response => {
this.results = response.data
})
}
}
</script>
hello_vue.js:
import Vue from 'vue'
import App from './app.vue'
document.addEventListener('DOMContentLoaded', () => {
document.body.appendChild(document.createElement('hello'))
const app = new Vue(App).$mount('hello')
console.log(app)
})
that allow me to insert the information in the views like:
<%= javascript_pack_tag 'hello_vue' %>
and works it show the information.
But when I try to make a new folder with new files like this :
app/javascript
└── datos
├── app2.vue
└── hello2_vue.js
app2:
<template>
<div id="app2">
<ul v-for="result in results">
<li>{{result.name}}</li>
</ul>
</div>
</template>
<script>
export default {
data: {
results: []
},
mounted(){
axios.get("xxxxxxxxxxxx")
.then(response => {
this.results = response.data
})
}
}
</script>
hello2:
import Vue from 'vue'
import App2 from './app2.vue'
document.addEventListener('DOMContentLoaded', () => {
document.body.appendChild(document.createElement('hello2'))
const app2 = new Vue(App2).$mount('hello2')
console.log(app2)
})
and them load the files:
<%= javascript_datos_tag 'hello2_vue' %>
it show this error:
undefined method `javascript_datos_tag' for #<#<Class:0x0055a86f9b0218>:0x007fd3cf6d9958>
Did you mean? javascript_cdata_section
javascript_tag
javascript_pack_tag

Sorry for that guy I just check my server foreman and apparently it needs to be re-start every time I add new views ans requests, in the foreman server like.
$foreman start

Related

Module not found: Error: Can't resolve 'vue/dist/vue.esm'

I added Vue to a Rails 6 app and I'm getting the following error:
ERROR in ./app/javascript/packs/hello_vue.js
Module not found: Error: Can't resolve 'vue/dist/vue.esm'
It's looking for it within app/javascript/packs but I'm not sure why.
The file vue.esm also does not exist within vue/dist directory.
My hello_vue.js file is:
import TurbolinksAdapter from 'vue-turbolinks'
import Vue from 'vue/dist/vue.esm'
import App from '../app.vue'
Vue.use(TurbolinksAdapter)
document.addEventListener('turbolinks:load', () => {
const app = new Vue({
el: '#hello',
data: () => {
return {
message: "Can you say hello?"
}
},
components: { App }
})
})
I also added the following to application.html.erb:
<head>
...
<%= javascript_pack_tag 'hello_vue' %>
<%= stylesheet_pack_tag 'hello_vue' %>
...
</head>
<body>
...
<div id='hello'>
{{message}}
<app></app>
</div>
...
</body>

Images not loading on page change using Link in NextJS

This is hard to explain without uploading my full project likely, but here goes. I think I've narrowed it down to some combination of getInitialProps() and getStaticProps(). When I use next/link to change pages images are not being loaded. If I browse directly to the page images will load fine. Project is fairly simple with only 2 pages, index.js and [slug].js. Here's both:
index.js
import React from 'react';
import Layout from '../components/layout';
import Seo from '../components/seo';
import Hero from '../components/hero';
import Forcast from '../components/forcast';
import { fetchAPI } from '../lib/api';
import ReactMarkdown from 'react-markdown';
const Home = ({ pages, homepage }) => {
return (
<Layout pages={pages}>
<Seo seo={homepage.seo} />
<Hero hero={homepage.hero} />
<Forcast />
<main className='main-content'>
<div className='fullwidth-block'>
<div className='container'>
<div className='post single'>
<div className='entry-content'>
<ReactMarkdown
source={homepage.Content}
escapeHtml={false}
transformImageUri={uri =>
uri.startsWith('http') ? uri : `${process.env.REACT_APP_IMAGE_BASE_URL}/${uri}`
}
/>
</div>
</div>
</div>
</div>
</main>
</Layout>
);
};
export async function getStaticProps() {
// Run API calls in parallel
const [pages, homepage] = await Promise.all([
fetchAPI('/pages'),
fetchAPI('/homepage'),
]);
return {
props: { pages, homepage },
revalidate: 1,
};
}
export default Home;
[slug].js
import ReactMarkdown from 'react-markdown';
import Layout from '../components/layout';
import Seo from '../components/seo';
import { fetchAPI } from '../lib/api';
const Page = ({ page, pages }) => {
const seo = {
metaTitle: page.Title,
metaDescription: page.seo.metaDescription,
shareImage: page.seo.shareImage,
}
return (
<Layout pages={pages}>
<Seo seo={page.seo} />
<main className='main-content'>
<div className='container'>
<div className='breadcrumb'>
</div>
</div>
<div className='fullwidth-block'>
<div className='container'>
<div className='row'>
<div className='content col-md-8'>
<div className='post single'>
<h2 className='entry-title'>{page.Title}</h2>
<ReactMarkdown
source={page.Content}
escapeHtml={false}
transformImageUri={uri =>
uri.startsWith('http') ? uri : `${process.env.REACT_APP_IMAGE_BASE_URL}${uri}`
}
/>
</div>
</div>
</div>
</div>
</div>
</main>
</Layout>
);
};
export async function getStaticPaths() {
const pages = await fetchAPI('/pages');
return {
paths: pages.map((page) => ({
params: {
slug: page.slug,
},
})),
fallback: false,
};
}
export async function getStaticProps({ params }) {
const pages = await fetchAPI(
`/pages?slug=${params.slug}`
);
return {
props: { page: pages[0], pages },
revalidate: 1,
};
}
export default Page;
This might also be a Strapi issue though I'm not sure.
The issue happens because the REACT_APP_IMAGE_BASE_URL is not exposed to the browser, and only available on the server.
To have it exposed to the browser you'll need to add the NEXT_PUBLIC_ prefix to it.
# .env.development
NEXT_PUBLIC_REACT_APP_IMAGE_BASE_URL=http://localhost:1337
Then in your code reference it using process.env.NEXT_PUBLIC_REACT_APP_IMAGE_BASE_URL.

Pass data from Rails template to Vue Instance

I've been trying to pass data from my Rails view to the Vue component as described here
Everything works much as expected, but I'm rather stumped as to how to access the data that I'm passing in via props. Not appearing in the Vue developer tools anywhere and I'm not able to find it by fiddling with/inside the Vue object.
Could someone point me in the right direction. I'm fairly green with Vue, so struggling to even know what to search for :/
show.html.erb
<%= javascript_pack_tag 'test_vue' %>
<%= stylesheet_pack_tag 'test_vue' %>
<%= content_tag :div, id: "test", data: {
message: "this wont!",
name: "nor will this!" }.to_json do %>
<% end %>
test.vue
<template>
<div id="app">
<p>{{test}}{{message}}{{name}}</p>
</div>
</template>
<script>
export default {
data: function () {
return {
test: 'This will display',
}
}
}
</script>
<style>
</style>
test_vue.js
import Vue from 'vue'
import Test from './test.vue'
document.addEventListener('DOMContentLoaded', () => {
const node = document.getElementById('test')
const props = JSON.parse(node.getAttribute('data'))
new Vue({
render: h => h(Test, { props })
}).$mount('#test');
})
Looks like all you need to do is declare the properties in your component:
<template>
<div id="app">
<p>{{test}}{{message}}{{name}}</p>
</div>
</template>
<script>
export default {
props: ["message","name"],
data: function () {
return {
test: 'This will display',
}
}
}
</script>
<style>
</style>
This would be the relevant documentation.
A child component needs to explicitly declare the props it expects to
receive using the props option

React router not redirect on the exact url

I am building an web application in which react-router is used. When i hit the url localhost:8080/user it works fine. When i hit localhost:8080/user/login it not works and console show unexpected tokken > what does it means? I could not understand the problem.
One more thing in this line of code when i changed to any other class then also its not working .
Routes.js
import React from 'react';
import UserBase from './UserBase.js';
import Dashboard from './Dashboard.js';
import Login from './Login.js';
// var ReactRouter = require('react-router');
// var Router = ReactRouter.Router;
// var Route = ReactRouter.Route;
import { Router, Route, IndexRoute, Link, IndexLink, browserHistory } from 'react-router'
var Routes = (
<Router history={browserHistory}>
<Route path="/" component={Login}/>
<Route path="user" component={UserBase}>
<IndexRoute component={Dashboard} />
<Route path="login" component={Login}/>
</Route>
</Router>
);
module.exports = Routes;
Login.js
import React from 'react';
class Login extends React.Component{
constructor(){
super();
}
render(){
return (
<div className="login">
<a className="hiddenanchor" id="signup"></a>
<a className="hiddenanchor" id="signin"></a>
<div className="login_wrapper">
<div className="animate form login_form">
<section className="login_content">
<form>
<h1>Login Form</h1>
</form>
</section>
</div>
<div id="register" className="animate form registration_form">
<section className="login_content">
<form>
<h1>Create Account</h1>
</form>
</section>
</div>
</div>
</div>
);
}
}
export default Login;
Routes js is working fine if I remove 'history={browserHistory}' means that if I use ugly url i.e. used with #. If I hit http://localhost:8080/#/user/login?_k=jtorvg is working fine then what will be the issue?
I use node server and express package to serve for every request.
var app = express();
app.use('/', express.static(path.join(__dirname, 'public')));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/index.html'));
});
webpack.config.js
module.exports = {
entry: "./app/components/EntryPoint.js",
output: {
filename:"public/bundle.js"
},
module : {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['react', 'es2015']
}
}
]
}
};
Yes. I got the answer after struggling of hours a very small mistake. At index page bundle.js script path has to be changed for the url like localhost:8080/user/dashboard.
Just add <script src="/bundle.js" /> instead of <script src="bundle.js" />

ASP.NET MVC and AngularJS

I am using AngularJS 1.2.2 (and am totally new to it) and MVC 5. I am trying to get a controller get called but it is not working.
As far as I could tell, the most appropriate 'shell' page is Views/Shared/_Layout.cshtml.
Therefore, in this page I have
<html data-ng-app="myApp">
Latter on in the Views/Shared/_Layout.cshtml I have
<div class="navbar navbar-fixed-top">
<div class="container">
<ul class="nav nav-pills" data-ng-controller="NavbarController">
<li data-ng-class="{'active':getClass('/home')}">Home</li>
<li data-ng-class="{'active':getClass('/albums')}">Albums</li>
</ul>
</div>
</div>
But when I click on either of these two links my getClass method does not get called. The file containing this method is being refernced. Here is the code it contains
app.controller('NavbarController', function ($scope, $location) {
$scope.getClass = function(path) {
if ($location.path().substr(0, path.length) == path) {
return true;
} else {
return false;
}
};
});
Any idea why this is not being called?
EDIT
My structure is such:
I have an app folder in the root.
In the app folder I have an app.js with this code
var app = angular.module('myApp', []);
app.config(function ($routeProvider) {
$routeProvider
.when('/Home',
{
controller: 'HomeController',
templateUrl: '/Views/Home/Index.cshtml'
})
.when('/Album',
{
controller: 'AlbumController',
templateUrl: '/View/Album/Index.cshtml'
})
.otherwise({ redirectTo: '/Home' });
});
(Incidentally I am guessing that by referring to my individual cshtml files like this I will get the correct behavior).
I have a controllers folder with the above NavbarController class.
I also have a services folder with my services in them.
In the _Layout file I have these js files referenced
#Scripts.Render("~/Scripts/angular.js")
#Scripts.Render("~/Scripts/angular-route.js")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
#Scripts.Render("~/app/app.js")
#Scripts.Render("~/app/controllers/navbarController.js")
#Scripts.Render("~/app/controllers/albumController.js")
#Scripts.Render("~/app/services/albumService.js")
There is an error in the console. It is
Error: [$injector:modulerr] Failed to instantiate module myApp due to: [$injector:unpr] Unknown provider: $routeProvider http://errors.angularjs.org/1.2.2/$injector/unpr?p0=%24routeProvider ...
It looks like you missed to include the ngRoute module in your dependency for myApp.
'use strict';
angular.module('myApp', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
//Your code
}]);

Resources