VueJS : Adding to existing HTML and handling imports - javascript

So I built a Single Page Application in VueJS which works nicely but the SEO sucks as expected, so I decided to make a normal HTML site with some pages having VueJS code (Remote hosting so no node else I would go SSR).
I followed this guide which works fin
I have a search.js which contains my VueJS instance and methods etc
Vue.component('todo-component', {
template: '#todo-component',
data: function () {
return {
items: [
{
id: 'item-1',
title: 'Checkout vue',
completed: false
}, {
id: 'item-2',
title: 'Use this stuff!!',
completed: false
}
],
newItem: ''
};
},
methods: {
addItem: function () {
if (this.newItem) {
var item = {
id: Math.random(0, 10000),
title: this.newItem,
completed: false
};
this.items.push(item);
this.newItem = '';
}
}
}
});
var app = new Vue({
el: '#vue-app'
});
However, I need to import stuff like axios and other components
if I add an import statement to the script above, it comes up with
import axios from "axios";
Uncaught SyntaxError: Unexpected identifier
Where should my imports go?

Since you are directly writing code running in the browser, you can simply include the axios cdn in your html code before search.js is loaded:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
As for components import, you can read more about component registration here. Generally if your components are registered globally via Vue.component('my-component', {}) syntax, you should be able to directly use it within your code.

You're missing axios library so add it as follow :
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
i'm also providing you of how to use it when you work with browser :
new Vue({
el: '#app',
data: {
dataReceived: '',
},
methods: {
getData() {
axios.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD')
.then((response) => {
this.dataReceived = response.data;
console.log(this.dataReceived);
return this.dataReceived;
})
}
}
})
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="https://unpkg.com/vue#2.5.17/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<button #click="getData" type="button">getData</button>
<p>dataReceived: {{ dataReceived }}</p>
</div>
</body>

Related

How to trigger Vue.js method from external JavaScript

I am trying to trigger a Vue.js method from a function that is in another JavaScript file. I have given the below code which I have tried.
sample.js
import vm from './vue.js';
function call( ) {
vm.$options.methods.displayData('I was called externally!')
}
call() // Here I am calling function
vue.js
var vm = new Vue({
el: '#app',
data: {
firstname : '' ,
lastname : ''
},
methods:{
displayData: function(s ) {
alert(s)
}
}
})
You don't need to access the $options object:
vm.displayData('I was called externally!')
This is simply using the instance to access its methods.
Edit for your comments below: To use the files without a bundler or es6 modules as you want, remove the import statement which is only for modules.
Here are the 3 complete files you would need for index.html, vue.js, sample.js:
index.html
<html>
<body>
<div id="app"></div>
<script src="https://unpkg.com/vue#2.6.12/dist/vue.js"></script>
<script src="vue.js"></script>
<script src="sample.js"></script>
</body>
</html>
vue.js
const vm = new Vue({
el: '#app',
data: () => ({
firstname : '',
lastname : ''
}),
methods:{
displayData: function(s) {
alert(s)
}
}
})
sample.js
function call( ) {
vm.displayData('I was called externally!')
}
call();

Axios not working on localhost Vue.js but working on external APIs

Whenever I use axios with external APIs, it grabs the data correctly and puts it into the info variable.
But whenever I try to use this on my own localhost environment, it doesn't return anything and there are no console errors to be seen.
vue js
<script type="module">
new Vue({
el: '#app',
data() {
return {
info: null
}
},
mounted: function () {
axios
.get("https://localhost:44331/Api/ShowRecipes/test/test")
.then(response => this.info = response.data.bpi)
}
})
</script>
api response json
[
{
"Id": 1,
"IngredientName": "something",
"IngredientCategory": "other",
"Calories": 100
},
html
<div id="app">
#RenderBody()
{{ info }}
</div>
And so on. Is this due to that you can't test it on localhost? Or did I do something wrong in my api?

How to import extrenal library on mounted hook in Nuxt Js?

I use conversation form package in my nuxt js project. I found custom component from github where used this package.
Component code:
<template>
<form id="my-form-element" cf-form></form>
</template>
<script>
import * as cf from 'conversational-form'
export default {
mounted: function() {
this.setupForm()
},
methods: {
setupForm: function() {
const formFields = [
{
tag: 'input',
type: 'text',
name: 'firstname',
'cf-questions': 'What is your firstname?'
},
{
tag: 'input',
type: 'text',
name: 'lastname',
'cf-questions': 'What is your lastname?'
}
]
this.cf = cf.startTheConversation({
options: {
submitCallback: this.submitCallback
},
tags: formFields
})
this.$el.appendChild(this.cf.formEl)
},
submitCallback: function() {
const formDataSerialized = this.cf.getFormData(true)
console.log('Formdata, obj:', formDataSerialized)
this.cf.addRobotChatResponse(
'You are done. Check the dev console for form data output.'
)
}
}
}
</script>
Now when I use this component get error message:
window is not defined
As solution of this error recomended this answer from stackowerflow
And after seen this answer I've change component code.
Changes:
1.Removedimport * as cf from 'conversational-form'
2.Replaced mounted() hook content to:
var cf = require('conversational-form')
this.setupForm()
After changes error fixed but package not work correctly. When call this library inside methods as this.cf nuxt js can't found cf var. How I can fix this problem?
Also you can see live demo of this package in vue js here
This is a rare situation that you may need to use the <client-only> tag. If you're using a version older than 2.9.0, then it is <no-ssr>. Docs found here.
Example:
<template>
<client-only>
<form id="my-form-element" cf-form></form>
</client-only>
</template>
<script>
import * as cf from 'conversational-form'
export default { ... }
</script>
This instructs Nuxt to only render the component client side, where window is defined.

Can't get Firebase data to display on simple Vue app

I'm trying to get a simple Vue+Firebase app running that allows you to send strings to the firebase database and have the messages be displayed using the "v-for" directive. However, I keep getting the error
Property or method "messages" is not defined on the instance but referenced during render
even though I'm pretty sure I'm using the correct syntax based on Vue's example on their site and the Vuefire github page to link up messages to the database. I can push to the database just fine, but for some reason I can't read the data from the database. I've been unable to get this to work for about a day and at this point any help is appreciated.
Here is my code for reference:
index.html:
<head>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = { ... };
firebase.initializeApp(config);
</script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="message" placeholder="Type a message!">
<button v-on:click="sendData">Send Data</button>
<br>
<h3 v-for="msg in messages">{{msg.value}}</h3>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
app.js:
var messageRef = firebase.database().ref('local/responses');
var app = new Vue({
el: '#app',
data: function () {
return {
message: ''
}
},
firebase: function () {
return {
messages: messageRef
}
},
methods: {
sendData: function () {
messageRef.push(this.message);
this.message = '';
}
}
});
You need to include the messages property in both the firestore return function as a database reference, as well as the data return function as an empty array for the database to bind to, as such.
var app = new Vue({
el: '#app',
data: function () {
return {
message: '',
messages: []
}
},
firebase: function () {
return {
messages: firebase.database().ref('local/responses')
}
},
methods: {
sendData: function () {
messageRef.push(this.message);
this.message = '';
}
}
});
This happens because you're trying to bind the Firestore reference to a piece of data that doesn't exist within your Vue instance, it needs that empty array for it to bind to the data property.

How to load and display data with React from an API running on localhost

I'm getting an error "app.js:16 Uncaught (in promise) TypeError: Cannot read property '0' of undefined" with my code below.
I'm trying to use React to display data from my Drupal API, that's running on my localhost.
In the React app, I'm using a simple HTTP server (python -m SimpleHTTPServer) to prevent XMLHttpRequest errors, and I have enabled CORS on my API. And instead of jQuery, I'm using Axios.
I can't get index.html to display anything else than the text "Event!", what am I doing wrong? Here is my app.js
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
title: ''
}
}
componentDidMount() {
var th = this;
this.serverRequest =
axios.get(this.props.source)
.then(function(event) {
th.setState({
title: event.title[0].value
});
})
}
componentWillUnmount() {
this.serverRequest.abort();
}
render() {
return (
<div>
<h1>Event!</h1>
<h2>{this.state.title}</h2>
</div>
);
}
}
ReactDOM.render(
<App source="http://localhost:8888/drupal/api/events" />,
document.getElementById('container')
);
And here is my index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App</title>
</head>
<body>
<div id="container"></div>
<script src="https://npmcdn.com/react#15.3.1/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom#15.3.1/dist/react-dom.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://npmcdn.com/jquery#3.1.0/dist/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
<script type="text/babel" src="js/app.js"></script>
</body>
</html>
I can't get anything else than the text "Event!" to show up, what am I doing wrong?
Here is a screenshot of part of my API, that shows an example of the title I'm trying to display "EspooCine".
If I add console.log on ComponentDidMount(), e.g.:
componentDidMount() {
var th = this;
this.serverRequest = axios.get(this.props.source).then(function(result) {
console.log(result);
})
}
Then I get the following on the console:
Axios promises yield a response object on success that has a data property containing the body of the response; it appears that you are trying to access the [0] property of the response object, not of its data, which will be the Array you expect. Also, it looks like there are other mistakes made accessing the structure. Try this or something similar:
axios.get(this.props.source).then(event => {
th.setState({
title: event.data[0].title[0].value
});
});

Categories

Resources