Writing javascript code in a component using vue - javascript

I am trying to make a component using Vue for my javascript code but it does not work.
My main goal is to create a component with vue or Vue3
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
</head
<body>
<div id="app">
<myelement name="ibrahim" age="12"></myelement>
</div>
</body>
<script>
Vue.component("myelement",{
props:["name","age"], // for arguments
template:`
<h1> welcome to my vue component,<br> name :{{name }} and age : {{age}}</h1>
`// template where my code template should be
})
var vm = new Vue({ // creating an object from Vue
el:"#app" // bind my created code to the id "app"
})
</script>
This code is working, but when I put a Javascript code in instead of html code. I got an error
this code I am using for my Javascript code, but the vue is not calling my javascript code . It is just calling my html code
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
</head
<body>
<h3>this page works</h3>
<div id="app">
<myelement ></myelement >
</div>
</body>
<script>
document.write("<h1>Header from document.write()</h1>");
var temp = "<h1>Hello from vue veriable</h1>"
Vue.component("myelement ",{
template:`
<script>
alert(1);
document.write("<h1>Header from document.write()</h1>");
</script>
`// template where my code template should be
})
var vm = new Vue({ // creating an object from Vue
el:"#app" // bind my created code to the id "app"
})
</script>
what I want to do is, when I create the tag in the page then the alert(1) will show up.

In vue, you cannot use script tag in template of components and you get below error:
[Vue warn]: Error compiling template: Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.
Instead you can put your javascript codes in created lifecycle hook. This hook is called when your component create:
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
</head>
<body>
<h3>this page works</h3>
<div id="app">
<myelement></myelement>
</div>
</body>
<script>
Vue.component("myelement", {
template: `<h2>Hello</h2>`,
});
var vm = new Vue({
el: "#app",
created() {
alert(1);
document.write("<h1>Header from document.write()</h1>");
},
});
</script>

I'm not sure but I think this code will work correctly:
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
</head>
<body>
<h3>this page works</h3>
<div id="app">
<myelement :message="variableAtParent"></myelement>
</div>
</body>
<script>
Vue.component("myelement", {
props: ['message'],
template: '<p>At child-comp, using props in the template: {{ message }}</p>',,
});
var vm = new Vue({
el: "#app",
data: {
variableAtParent: 'DATA FROM PARENT!'
}
});
</script>

Related

Vue JS component not working in blade page

I want to load vue component in laravel blade file, but my changes are not reflected in laravel blade file. my vue file content is not loaded into blade file, example component return empty. There is no error in console, please help me to solve my problem.
**Blade file**
<!DOCTYPE html>
<html>
<head>
<script defer src="{{ mix('js/example.js') }}"></script>
<link rel="stylesheet" href="{{ mix('css/app.css') }}" />
</head>
<body>
<div id="app">
<example></example>
</div>
</body>
</html>
**
**example.js**
require('./bootstrap');
window.Vue = require('vue');
Vue.component('example', require('./components/Example.vue').default);
const app = new Vue({
el: '#app'
});
**
<!-- begin snippet: js hide: false console: true babel: false -->
Example.vue
<template>
<div class="container">
<h1>Example Code</h1>
</div>
</template>
<script>
export default {
}
</script>
Just change your js code like below way
require('./bootstrap');
import Vue from 'vue'
import Example from "./components/Example"
const app = new Vue({
el: '#app',
components: { Example },
});
Then you have to build the assets. Run below command
npm run dev

Cannot pass props from Laravel blade file to Vue Component

I'm trying to pass value from Laravel to Vue. But the props I get is always undefined (from console.log). I checked it's not the camel case issue. I really can't find where is the issue. Can anyone help, please?
PS. I'm a laravel and Vue beginner. Thank you very much
blade.php file:
#extends('layouts.subject')
#section('content')
<script src="{{ asset('js/subject/subjectapp.js') }}" defer></script>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<sample message="HELLO"></sample>
</div>
</div>
</div>
</div>
</div>
#endsection
subjectapp.js file:
require('../bootstrap');
window.Vue = require('vue');
import 'babel-polyfill'
import Vuetify from 'vuetify';
import Sample from '../components/subject/Sample.vue';
Vue.use(Vuetify);
const sample = new Vue({
el: 'sample',
vuetify: new Vuetify(),
components: {
Sample
},
render: h => h(Sample),
});
Sample.vue file
<template>
<v-app>
<div class="row">
<div class="col border m-2">
MESSAGE
{{message}}
</div>
</div>
</v-app>
</template>
<script>
export default {
props: ['message'],
created() {
console.log(this.message);
},
}
</script>
Edit:
extra info of my app:
data CANNOT be passed from blade.php to a vue component(A.vue) nested inside.
Data CAN be passed from a Vue component(A.vue) nested in the blade.php, to a vue component(B.vue) nested in that component(A.vue).
You can add this to the end of your blade.php file
<script>
window.prop1 = somePropValue;
window.prop2 = somePropValue;
</script>
and access it on your vue file by calling window.prop1
This solution works for me. Here are my files:
<html>
<head>
<script src="{{ asset('js/app.js') }}" defer></script>
</head>
<body>
<div id="app">
<main class="py-sm-4">
<chat-component #if(isset($create_message)) user="{{ $create_message }}" #endif></chat-component>
</main>
</div>
</body>
<script>
window.Laravel = {!! json_encode([
'auth' => auth() -> check() ? auth() -> user() -> id : null,
])!!};
window.LaravelUrl = "{{ url('') }}"
window.user_id = "{{Auth::id()}}"
</script>
</html>
app.js file:
require('./bootstrap');
window.Vue = require('vue');
import WebRTC from 'vue-webrtc'; //video call plugin, not relevant to the answer
Vue.use(WebRTC); //video call plugin, not relevant to the answer
Vue.component('chat-component', require('./components/ChatComponent.vue'));
const app = new Vue({
el: '#app',
});
Vue example usages:
axios.post(window.LaravelUrl + `/send/${this.friend.session.id}`)
//
axios.post(window.LaravelUrl + "/send_calling_info", {
session_id: this.friend.session.id,
receiver_id: this.friend.id,
caller_id: window.user_id
})
//
return this.session.blocked_by == window.Laravel.auth;
and some other usages inside axios.post()

VueJs filters have no effect

Simple code example
<!DOCTYPE html>
<html>
<head>
<title>My first Vue app</title>
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.10/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<style>
</style>
</head>
<body>
<div id="app">
<h1>Bitcoin Price Index</h1>
<div v-for="currency in info">
{{ currency.description }}
<span v-html="currency.symbol"></span>{{ currency.rate_float || currencyToDeciaml }}
</div>
</div>
<script>
const app = new Vue({
el : '#app',
data : {
info : null,
},
filters : {
currencyToDeciaml(val) {console.log(`foo`);
return Number(val).toFixed(2);
}
},
// Dom is ready so now load the data
mounted() {
axios.get(`https://api.coindesk.com/v1/bpi/currentprice.json`)
.then(response => this.info = response.data.bpi);
},
});
</script>
</body>
</html>
I am trying to apply a simple filter currencyToDeciaml but it doesn't even get executed and foo does not display. I cannot seem to figure it out. Any help would be appreciated.
The correct syntax for filters is this:
{{ currency.rate_float | currencyToDeciaml }}
with only one pipe

Vue js with simple JavaScript Vue is undefined

I am trying to understand how vue works. To do that I simplify it as much as possible, hence no webpack no CDNs or any other packages (unless its a necessity).
So, Came up with this but trying to inject a simple a variable into html gives vue is undefined error.
*vue.js file is taken from npm vue package.
<html>
<head>
<script src="vue.js"></script>
<script>
new vue({
data: 'This must be injected'
}).$mount('#app');
</script>
</head>
<body>
<div id="app">
<p> {{ data }} </p>
</div>
<h1>This is a sample header</h1>
</body>
</html>
You need to have Vue load after the Dom is ready so it can find the element to attach itself to — don't put it in the head. Also it's upper-case Vue. And Data can't just be a naked property it should be a function that returns an object with your properties (it can also be an an object, but it's not recommended once the app starts getting bigger).
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<p> {{ data }} </p>
</div>
<h1>This is a sample header</h1>
<script>
Vue.config.productionTip = false
new Vue({
data(){ return {
data: 'This must be injected'
}
}
}).$mount('#app');
</script>
There are a few problems in your code.
vue should be Vue
data should be an Object or Function - https://v2.vuejs.org/v2/api/#data
<html>
<head>
</head>
<body>
<div id="app">
<p> {{ myText }} </p>
</div>
<h1>This is a sample header</h1>
<script src="vue.js"></script>
<script>
new Vue({
data: {
myText: 'This must be injected'
}
}).$mount('#app');
</script>
</body>
</html>
I think the data must have an object as it's value.
<html>
<head>
<script src="vue.js"></script>
<script>
new Vue({
data: {
txt: 'This must be injected'
}
}).$mount('#app');
</script>
</head>
<body>
<div id="app">
<p> {{ txt }} </p>
</div>
<h1>This is a sample header</h1>
</body>
</html>

how to use vue.js in simple web application?

I am gonna planning to use vue.js in a web application. but it could not loaded and not fired html in browser. Please look at my below code:
<!DOCTYPE html>
<html>
<head>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
});
</script>
</head>
<body>
<div id="app">
{{ message }}
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</body>
</html>
The problem is you're trying to create Vue instance before vue.js is loaded, so I think if you put your code after vue.js, your application will work fine.
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="app">
{{ message }}
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
});
</script>
</body>
</html>

Categories

Resources