How to created dynamic/raw HTML with VueJS - javascript

I would like to transform the span into a real element. When I try this way the appendChild gives me an error because the variable is a string and not and object. Any ideas?
export default{
data(){
....
}
methods:{
update_period: function(event){
var start = moment(event.start).format('M/D/Y'),
end = moment(event.end).format('M/D/Y');
var span = `<span #click="remove">{{ start }} - {{ end }}</span>`
this.$refs.spans.appendChild(span);
},
remove: function(event){
event.target.remove()
}
}
}
<div ref="spans">
</div>

You can get the same result in this way:
<template>
<div>
<span #click="remove" v-if="period">{{ period }}</span>
</div>
</template>
<script>
export default {
data() {
return {
period: null,
}
},
methods:{
update_period(event) {
this.period = moment(event.start).format('M/D/Y') + ' - ' + moment(event.end).format('M/D/Y')
},
remove() {
this.period = null;
}
}
}
</script>

Related

Adding custom HTML element inside template using functions Vue.js

Is there any way to render html element with custom properties inside template tag using javascript functions?
Example what I try to achieve:
<template>
<div class="test">
{{ testFunction(param1,param2,param3) }}
</div>
</template>
<script>
export default {
....
methods: {
testFunction(param1,param2,param3) {
return `<button #click="function()">Click</button>`;
}
}
};
</script>
Directly you will get interpolated html, like this
<button #click="function()">Click</button>
Even if you fix it using the v-html directive to output raw HTML the button will still not work.
The right way is to use Render Functions like this:
const myComponent3 = {
setup(props) {
return () => h('button',
{
onClick(event) {
alert('Click');
}
},
'Click Me!'
)
}
}
Here is the playground with samples:
const { createApp, h } = Vue;
const myComponent1 = {
template: '#my-component',
methods: {
testFunction(par1) {
return `<button #click="function()">Click</button>`;
}
}
}
const myComponent2 = {
template: '<div v-html="rawHTML()"></div>',
methods: {
myClick() {
alert('Click');
},
rawHTML(par1) {
return '<button #click="myClick()">Click</button>';
}
}
}
const myComponent3 = {
setup(props) {
return () => h('button',
{
onClick(event) {
alert('Click');
}
},
'Click Me!'
)
}
}
const App = {
components: {
myComponent1, myComponent2, myComponent3
}
}
const app = createApp(App)
app.mount('#app')
<div id="app">
My Component 1: <my-component1></my-component1><br/>
My Component 2: <my-component2></my-component2><br/>
My Component 3: <my-component3></my-component3><br/>
</div>
<script src="https://unpkg.com/vue#3/dist/vue.global.prod.js"></script>
<script type="text/x-template" id="my-component">
<div class="test">
{{ testFunction( param1 ) }}
</div>
</script>

Why is function is not defined at eval?

I have the following Pokemon.vue file:
<template>
<div class="pokemon">
<h1>Pokemon Overview</h1>
<div class v-for="pokemon in pokemonArray" :key="pokemon.id">
<p>{{ pokemon.name }}</p>
<p>{{ pokemon.number }}</p>
<p>{{ pokemon.height }}</p>
<p>{{ pokemon.weight }}</p>
<p>{{ pokemon.types }}</p>
</div>
<button #click="AddPokemon">AddPokemon</button>
</div>
</template>
<script>
import axios from "axios";
import db from "#/firebase/init";
export default {
name: "Pokemon",
data() {
return {
pokemonArray: [],
};
},
methods: {
CapitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
},
AddPokemon() {
for (var i = 520; i < 524; i++) {
axios.get("https://pokeapi.co/api/v2/pokemon/" + i).then((response) => {
var types = [];
for (var j = 0; j < response.data.types.length; j++) {
types.push(response.data.types[j].type.name);
}
db.collection("pokemon").add({
number: i,
name: CapitalizeFirstLetter(response.data.name),
weight: response.data.weight / 10,
height: response.data.height / 10,
types: types,
image:
response.data.sprites.other["official-artwork"].front_default,
});
});
}
},
},
created() {
//Fetch data from the firestore
db.collection("pokemon")
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
let pokemon = doc.data();
this.pokemonArray.push(pokemon);
});
});
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
However, when I click the button that runs the AddPokemon function I get hit with
CapitalizeFirstLetter is not defined at eval
And I don't understand why this is happening. I'm clearly missing something, but to my understanding it should be fine to use a different method from "methods", but this might not be the case? Any help is greatly appreciated.
It should be this.CapitalizeFirstLetter:
db.collection("pokemon").add({
number: i,
name: this.CapitalizeFirstLetter(response.data.name),
weight: response.data.weight / 10,
height: response.data.height / 10,
types: types,
image:
response.data.sprites.other["official-artwork"].front_default,
});
try this.CapitalizeFirstLetter
You need use this for access vue instance, example, this.CapitalizeFirstLetter(string)

this.$el of Vue components always reference the same dom element

I have a component “MText”,the main code is as follows :
<template>
<vue-draggable-resizable #click="deleteFun">
</vue-draggable-resizable>
</template>
export default {
method:{
deleteFun () {
this.$el.remove();
}
}}
and in another file,I have a function like this
function createText(){
let MyComponent =Vue.extend({
template:"<MText></MText>",
components:{MText},
data () {
return {}
}})
return new MyComponent(); }
and I have a button,click event bind a function “addText”,like this
addText(){
let text = createText();
let panel = document.getElementById("palette");
let tp_dom = document.createElement("div");
tp_dom.setAttribute("id","id");
panel.appendChild(tp_dom);
text.$mount(tp_dom);
}
the quesition is that when I run “addText” twice, the dom “#palette”
have two “MText” elements,then,I click the second “MText” element,why
the first “MText” is deleted;“this.$el” always reference the first
“MText”
I have no idea what your problem is, but here's a working example:
https://jsfiddle.net/oddswe36/
let i = 0;
// Register your component globally
Vue.component('MText', {
template: `
<div #click="removeMe">click to remove me {{ counter }}</div>
`,
data() {
return {
counter: i++
}
},
methods: {
removeMe() {
this.$el.remove()
}
}
})
function createText() {
const MyComponent = Vue.extend({
template:"<MText></MText>",
})
return new MyComponent();
}
function addText() {
const text = createText();
const panel = document.getElementById("palette");
const tp_dom = document.createElement("div");
tp_dom.setAttribute("id","id");
panel.appendChild(tp_dom);
text.$mount(tp_dom);
};
addText();
addText();
addText();
addText();
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="palette"></div>

How open first tab with vuejs?

How do I open the first tab with VueJS? I have made two components but I don't know how to open the first tab automatically. This is what I've tried, but it doesn't work:
In mounted when i do console.log(this.tabs) return only 0 but before i do this.tabs = this.$children
Tabs.vue
<template>
<div>
<div class="tabs-header">
<ul>
<li v-for="tab in tabs" :key="tab.id" :class="{'is-active' : tab.isActive}">
<a :href="tab.href" #click="selectTab(tab)">{{ tab.name }}</a>
</li>
</ul>
</div>
<div class="content">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
name: "Tabs",
data: function(){
return { tabs: null };
},
created: function() {
this.tabs = this.$children;
//this.tabs[0].isActive = true;
},
methods: {
selectTab (selectedTab){
this.tabs.forEach(tab => {
tab.isActive = (tab.href == selectedTab.href);
});
}
}
}
</script>
This is my second components $children
Tab.vue
<template>
<div v-show="isActive">
<slot></slot>
</div>
</template>
<script>
export default {
name: "Tabs",
props: {
name: { require: true },
selected: { default: false }
},
data() {
return { isActive: false }
},
computed: {
href() {
return '#' + this.name.toLowerCase().replace(/ /g,'-');
}
},
mounted() {
this.isActive = this.selected;
},
methods: {
select(){
this.isActive = true;
}
}
}
</script>
This line doesn't work:
//this.tabs[0].isActive = true;
I copy pasted the code from laracasts.com/series/learn-vue-2-step-by-step/episodes/11 and the first tab is opened by default.
It is the case because in the html, you have :selected=true set on the first tab.
If you want to open the second tab by default, move :selected=true to the second tab, like this : https://jsfiddle.net/ahp3zzte/1/
If you want to change the default tab dynamically, remove :selected=true from the html and call the selectTab method in the js. Also note that to do this, you need to use mounted instead of created. Check this other fiddle : https://jsfiddle.net/0402y2ew/

VueJs watching deep changes in object

I have this 3 components in VueJS. The problem i want to solve is: When i click at vehicle component, it needs to be selected (selected = true) and other vehicles unselected.
What i need to do for two-way data binding? Because i'm changing this selected property in VehiclesList.vue component and it also need to be changed in Monit.vue (which is a parent) and 'Vehicle.vue' need to watch this property for change class.
Also problem is with updating vehicles. In Monit.vue i do not update full object like this.vehicles = response.vehicles, but i do each by each one, and changing only monit property.
Maybe easier would be use a store for this. But i want to do this in components.
EDITED:Data sctructure
{
"m":[
{
"id":"v19",
"regno":"ATECH DOBLO",
"dt":"2017-10-09 13:19:01",
"lon":17.96442604,
"lat":50.66988373,
"v":0,
"th":0,
"r":0,
"g":28,
"s":"3",
"pow":1
},
{
"id":"v20",
"regno":"ATECH DUCATO_2",
"dt":"2017-10-10 01:00:03",
"lon":17.96442604,
"lat":50.6698494,
"v":0,
"th":0,
"r":0,
"g":20,
"s":"3"
},
]
}
Monit.vue
<template>
<div class="module-container">
<div class="module-container-widgets">
<vehicles-list :vehicles="vehicles"></vehicles-list>
</div>
</div>
</template>
<script>
import VehiclesList from '#/components/modules/monit/VehiclesList.vue';
export default {
name: "Monit",
data (){
return {
vehicles: null
}
},
components: {
VehiclesList
},
methods: {
getMonitData(opt){
let self = this;
if (this.getMonitDataTimer) clearTimeout(this.getMonitDataTimer);
this.axios({
url:'/monit',
})
.then(res => {
let data = res.data;
console.log(data);
if (!data.err){
self.updateVehicles(data.m);
}
self.getMonitDataTimer = setTimeout(()=>{
self.getMonitData();
}, self.getMonitDataDelay);
})
.catch(error => {
})
},
updateVehicles(data){
let self = this;
if (!this.vehicles){
this.vehicles = {};
data.forEach((v,id) => {
self.vehicles[v.id] = {
monit: v,
no: Object.keys(self.vehicles).length + 1
}
});
} else {
data.forEach((v,id) => {
if (self.vehicles[v.id]) {
self.vehicles[v.id].monit = v;
} else {
self.vehicles[v.id] = {
monit: v,
no: Object.keys(self.vehicles).length + 1
}
}
});
}
},
},
mounted: function(){
this.getMonitData();
}
};
</script>
VehiclesList.vue
<template>
<div class="vehicles-list" :class="{'vehicles-list--short': isShort}">
<ul>
<vehicle
v-for="v in vehicles"
:key="v.id"
:data="v"
#click.native="select(v)"
></vehicle>
</ul>
</div>
</template>
<script>
import Vehicle from '#/components/modules/monit/VehiclesListItem.vue';
export default {
data: function(){
return {
isShort: true
}
},
props:{
vehicles: {}
},
methods:{
select(vehicle){
let id = vehicle.monit.id;
console.log("Select vehicle: " + id);
_.forEach((v, id) => {
v.selected = false;
});
this.vehicles[id].selected = true;
}
},
components:{
Vehicle
}
}
</script>
Vehicle.vue
<template>
<li class="vehicle" :id="data.id" :class="classes">
<div class="vehicle-info">
<div class="vehicle-info--regno font-weight-bold"><span class="vehicle-info--no">{{data.no}}.</span> {{ data.monit.regno }}</div>
</div>
<div class="vehicle-stats">
<div v-if="data.monit.v !== 'undefined'" class="vehicle-stat--speed" data-name="speed"><i class="mdi mdi-speedometer"></i>{{ data.monit.v }} km/h</div>
</div>
</li>
</template>
<script>
export default {
props:{
data: Object
},
computed:{
classes (){
return {
'vehicle--selected': this.data.selected
}
}
}
}
</script>
Two-way component data binding was deprecated in VueJS 2.0 for a more event-driven model: https://v2.vuejs.org/v2/guide/components.html#One-Way-Data-Flow
This means, that changes made in the parent are still propagated to the child component (one-way). Changes you make inside the child component need to be explicitly send back to the parent via custom events: https://v2.vuejs.org/v2/guide/components.html#Custom-Events or in 2.3.0+ the sync keyword: https://v2.vuejs.org/v2/guide/components.html#sync-Modifier
EDIT Alternative (maybe better) approach:
Monit.vue:
<template>
<div class="module-container">
<div class="module-container-widgets">
<vehicles-list :vehicles="vehicles" v-on:vehicleSelected="onVehicleSelected"></vehicles-list>
</div>
</div>
</template>
<script>
import VehiclesList from '#/components/modules/monit/VehiclesList.vue';
export default {
name: "Monit",
data (){
return {
vehicles: null
}
},
components: {
VehiclesList
},
methods: {
onVehicleSelected: function (id) {
_.forEach((v, id) => {
v.selected = false;
});
this.vehicles[id].selected = true;
}
...other methods
},
mounted: function(){
this.getMonitData();
}
};
</script>
VehicleList.vue:
methods:{
select(vehicle){
this.$emit('vehicleSelected', vehicle.monit.id)
}
},
Original post:
For your example this would probably mean that you need to emit changes inside the select method and you need to use some sort of mutable object inside the VehicleList.vue:
export default {
data: function(){
return {
isShort: true,
mutableVehicles: {}
}
},
props:{
vehicles: {}
},
methods:{
select(vehicle){
let id = vehicle.monit.id;
console.log("Select vehicle: " + id);
_.forEach((v, id) => {
v.selected = false;
});
this.mutableVehicles[id].selected = true;
this.$emit('update:vehicles', this.mutableVehicles);
},
vehilcesLoaded () {
// Call this function from the parent once the data was loaded from the api.
// This ensures that we don't overwrite the child data with data from the parent when something changes.
// But still have the up-to-date data from the api
this.mutableVehilces = this.vehicles
}
},
components:{
Vehicle
}
}
Monit.vue
<template>
<div class="module-container">
<div class="module-container-widgets">
<vehicles-list :vehicles.sync="vehicles"></vehicles-list>
</div>
</div>
</template>
<script>
You still should maybe think more about responsibilities. Shouldn't the VehicleList.vue component be responsible for loading and managing the vehicles? This probably would make thinks a bit easier.
EDIT 2:
Try to $set the inner object and see if this helps:
self.$set(self.vehicles, v.id, {
monit: v,
no: Object.keys(self.vehicles).length + 1,
selected: false
});

Categories