Dynamically change <style> inside a Single File Component - vue.js

Is it possible to dynamically change the content of a scoped inside a Single File Component?

You could do it using the v-html directive.
Since I don't know your actual code I will just give you the code for a basic proof of concept.
In the template...
<template>
<div>
<head v-html="styles"></head>
<div class="test">
<p>change this paragraph</p>
</div>
<textarea name="" id="" cols="30" rows="10" v-model="csscode"> </textarea>
</div>
</template>
In the script...
<script>
export default {
data() {
return{
csscode: null,
styles: null,
}
},
watch:{
csscode(val){
this.styles = '<style>' + val + '</style>';
}
}
}
</script>

Inside style tag, no. Its not possible because of build extracts a .css file.
But as an alternative you can use javascript object as an style object.
var app = new Vue({
el: '#app',
data: function(){
return {
textAreaStyle: {border: '2px solid blue', color: 'red', width: '500px', height: '300px'}
}
},
methods: {
updateStyle (event) {
this.$set(this.$data, 'textAreaStyle', JSON.parse(event.target.value));
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
<textarea :style="textAreaStyle" #change="updateStyle">{{textAreaStyle}}</textarea>
</div>

Related

Conditional CSS proprety set in computed object doesn't evaluate on the browser

I am trying to make the header element's height size to change depending on a criteria. I set the desired heights in a headerHeightClass inside a computed object but it doesn't seem to work.
<template>
<header :class="['w-full', 'text-sm', 'headerHeightClass']">
<div class="fixed top-0 left-0 w-full h-16 bg-white">
<!--Some irrelevant html code -->
</div>
</header>
</template>
<script>
export default {
name: "MainNav",
components: {},
data() {
return {
isLoggedIn: false,
};
},
computed: {
headerHeightClass() {
return {
"h-16": !this.isLoggedIn,
"h-32": this.isLoggedIn,
};
},
},
methods: {
loginUser() {
this.isLoggedIn = true;
},
},
};
</script>
I also tried:
computed: {
headerHeightClass() {
return this.isLoggedIn? "h-32": "h-16",
},
},
The headerHeightClass appears as a simple string in the browser.
You need to write it like this instead of using headerHeightClass as a string (remove ' ')
<template>
<header :class="['w-full', 'text-sm', headerHeightClass]">
<div class="fixed top-0 left-0 w-full h-16 bg-white">
<!--Some irrelevant html code -->
</div>
</header>
</template>
This can also be written without using computed
<template>
<header :class="[
'w-full text-sm',
{
'h-16':!isLoggedIn,
'h-32':isLoggedIn,
}
]">
<div class="fixed top-0 left-0 w-full h-16 bg-white">
<!--Some irrelevant html code -->
</div>
</header>
</template>
You can give a try like this (Just for a demo purpose I used Vue 2 version) :
Vue.component('headerComponent', {
props: ['msg'],
template: '<p>{{ msg }}</p>'
});
var app = new Vue({
el: '#app',
data: {
isLoggedIn: true
}
});
.w-full {
background-color: gray;
width: 100%;
}
.text-sm {
font-size: 12px;
}
.h-16 {
height: 16px;
}
.h-32 {
height: 32px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<header-component
msg="This is a header component"
:class="['w-full text-sm', { 'h-16':!isLoggedIn, 'h-32':isLoggedIn }]">
</header-component>
</div>

if-emoji lookup table with Vue

I'm using the npm module if-emoji to detect whether a user can view emojis or not. There is a similar tool in Modernizr.
If the user can't view emojis, I'm displaying an image of the emoji instead. So my Vue HTML looks like this:
<h2 v-if="this.emojis">😄</h2>
<h2 v-if="!this.emojis"><img src="https://example.com/emoji.png">/h2>
Does this still download the image for users who can view emojis, therefore using bandwidth unecessarily?
And is there a more efficient way of doing this, so that I don't need to go and add v-if every time I use an emoji? Can there be some sort of lookup table, if there's an emoji and !this.emojis?
You can solve this also by creating your own vue.component
<emojiorimage usesmily="false" smily="😄" imgpath="https://i.stack.imgur.com/QdqVi.png"></emojiorimage>
that capsulates the decision if image or smily inside itself.
var app = new Vue({
el: "#app",
data: function(){
return {
extendedCost: 0,
}
},
components: { "emojiorimage" : {
template : `
<h2>
usesmily is {{usesmily}}<br/>
<div v-if="usesmily === 'true'">{{ smily }}</div>
<div v-else><img :scr="imgpath" width="50" height="50" :alt="imgpath" /></div>
</h2>`,
props: ["usesmily", "smily", "imgpath"],
}}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h1>Emoji or Image</h1>
<emojiorimage
usesmily="false"
smily="😄"
imgpath="https://i.stack.imgur.com/QdqVi.png"
></emojiorimage>
<emojiorimage
usesmily="true"
smily="😎"
imgpath="https://i.stack.imgur.com/QdqVi.png"
></emojiorimage>
</div>
You can then feed it the isemoji from your npm package that you query once and store somewhere.
For seperate vue files it would look kind of like this:
emojiorimage.vue
<template>
<h2>
<div v-if="usesmily === 'true'">{{ smily }}</div>
<div v-else><img :scr="imgpath" width="50" height="50"
:alt="imgpath" /></div>
</h2>
</template>
<script>
export default {
props: ["usesmily", "smily", "imgpath"],
};
</script>
App.vue
<template>
<div id="app">
<h1>Emoji or Image</h1>
<emojiorimage
usesmily="false"
smily="😄"
imgpath="https://i.stack.imgur.com/QdqVi.png"
/>
<emojiorimage
usesmily="true"
smily="😎"
imgpath="https://i.stack.imgur.com/QdqVi.png"
/>
</div>
</template>
<script>
import emojiorimage from "./components/emojiorimage.vue";
export default {
components: {
emojiorimage,
},
};
</script>
index.html
<div id="app"></div>
index.js
import Vue from "vue";
import App from "./App";
Vue.config.productionTip = false;
new Vue({
el: "#app",
template: "<App/>",
components: { App }
});
to get:
Learning resources:
https://v2.vuejs.org/v2/guide/components.html
https://v2.vuejs.org/v2/guide/single-file-components.html
This should work as well:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<h2 v-if="true">😄</h2>
<h2 v-else><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png" width=15 height=15></h2>
<h2 v-if="false">😄</h2>
<h2 v-else><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png" width=15 height=15></h2>
The v-if part only is part of the sourcecode if the statement is true - else the else statement is in instead. If the img tag is not part of the loaded source the image wont be loaded.
<h2 v-if="emojis">😄</h2>
<h2 v-else><img src="https://example.com/emoji.png"></h2>
Is probably the only way to improve your code as #Patrick Artner pointed out.
You do not need this. in the template
To the question if the image is loaded if it is not shown the simple answer is no. Vue only renders v-ifs when they are needed and does not render it - the image is loaded only if !emojis.
Thanks to #PatrickArtner who posted the idea of using a Vue component to render the emoji / image. Here is my final solution, which resizes the emoji / image to fit the surrounding text — it uses fitty to resize the emojis, and sets the images to height:1em;.
Emoji.vue
<template>
<div class="emojiContainer">
<span id="fittyEmoji" v-if="emojis">{{ insert }}</span>
<img v-if="!emojis" :src="insert" class="emojiImage">
</div>
</template>
<style scoped>
.emojiContainer {
display: inline;
}
.emojiImage {
height:1em;
}
</style>
<script src="fitty.min.js"></script>
<script>
import fitty from 'fitty';
import ifEmoji from 'if-emoji'
export default {
name: 'Emoji',
props: ['name'],
data: function() {
return {
insert: "",
emojis: false,
}
},
methods: {
insertEmoji(){
var names = ['frog', 'fire']
var emojis = ['🐸','🔥']
var urls = ['https://example.com/frog.png',
'https://example.com/fire.png']
if (this.emojis) {
this.insert = emojis[names.indexOf(this.name)];
} else {
this.insert = urls[names.indexOf(this.name)];
}
fitty('#fittyEmoji')
}
},
beforeMount() {
if (ifEmoji('🐸')) {
this.emojis = true;
} else {
this.emojis = false;
}
this.insertEmoji();
}
}
</script>
Then in your parent components you can just insert like this:
<template>
<div id="app">
<h1><Emoji name='frog'/> Frog Facts</h1>
<p>Lorem ipsum <Emoji name='fire'/><p>
</div>
</template>
<script>
import Emoji from '#/components/Emoji.vue'
export default {
components: {
Emoji,
},
};
</script>

Vue open a component in a component

In App.vue I have a button to open a component . Inside the component BigForm, I also have a button to open a component named, . But as I open the component. Vue re-render the page with the warning:
The "data" option should be a function that returns a per-instance value in component definitions.
App.Vue
<template>
<div id="app">
<button #click="showModal()">Show</button>
<BigForm v-if="modal" />
</div>
</template>
<script>
import BigForm from "./components/BigForm";
export default {
name: "App",
components: {
BigForm,
},
data() {
return {
modal: false,
};
},
methods: {
showModal() {
this.modal = !this.modal;
},
},
};
</script>
BigForm.vue:
<template>
<div class="hello">
<form style="height: 300px; width: 300px; background-color: green">
<button #click="showSmallForm()">Show small form</button>
<SmallForm
v-if="toggleSmallForm"
style="width: 100px; height: 100px; background-color: yellow"
/>
</form>
</div>
</template>
<script>
import SmallForm from "./SmallForm";
export default {
name: "HelloWorld",
components: {
SmallForm,
},
data() {
return {
toggleSmallForm: false,
};
},
methods: {
showSmallForm() {
this.toggleSmallForm = !this.toggleSmallForm;
},
},
};
</script>
And SmallForm.vue:
<template>
<form>
<input placeholder="Small form input" />
<button>This is small form</button>
</form>
</template>
This is the code to my example in codesandbox:
https://codesandbox.io/s/late-cdn-ssu7f?file=/src/App.vue
The problem is not related to Vue itself but the HTML.
When you use <button> inside <form>, the default type of the button is submit (check this) - when you click the button, the form is submitted to the server causing the page to reload.
You can prevent that by explicitly setting type <button type="button"> (HTML way) or by preventing default action (Vue way) <button #click.prevent="showSmallForm()">Show small form</button> (see event modifiers)
Also note that using <form> in another <form> is not allowed in HTML

How to use x-template to separate out template from Vue Component

Tried to separate out template from Vue Component as below but it does not work.
Referencing only vue.js file and not browsify.
Vue.component('my-checkbox', {
template: '#checkbox-template',
data() {
return { checked: false, title: 'Check me' }
},
methods: {
check() { this.checked = !this.checked; }
}
});
<script type="text/x-template" id="checkbox-template">
<div class="checkbox-wrapper" #click="check">
<div :class="{ checkbox: true, checked: checked }"></div>
<div class="title"></div>
</div>
</script>
Or any alternate way to separate out template from vue component.
You define X-Templates in your HTML file. See below for a brief demo
// this is the JS file, eg app.js
Vue.component('my-checkbox', {
template: '#checkbox-template',
data() {
return { checked: false, title: 'Check me' }
},
methods: {
check() { this.checked = !this.checked; }
}
});
new Vue({el:'#app'})
/* CSS file */
.checkbox-wrapper {
border: 1px solid;
display: flex;
}
.checkbox {
width: 50px;
height: 50px;
background: red;
}
.checkbox.checked {
background: green;
}
<!-- HTML file -->
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.17/dist/vue.min.js"></script>
<script type="text/x-template" id="checkbox-template">
<div class="checkbox-wrapper" #click="check">
<div :class="{ checkbox: true, checked: checked }"></div>
<div class="title">{{ title }}</div>
</div>
</script>
<div id="app"> <!-- the root Vue element -->
<my-checkbox></my-checkbox> <!-- your component -->
</div>
Sorry for my bad english it's not my main language!
Try it!
You need generate two file in same directory:
path/to/checkboxComponent.vue
path/to/checkboxComponent.html
In checkboxComponent.vue file
<script>
// Add imports here eg:
// import Something from 'something';
export default {
template: require('./checkboxComponent.html'),
data() {
return { checked: false, title: 'Check me' }
},
methods: {
check() { this.checked = !this.checked; }
}
}
</script>
In checkboxComponent.html file
<template>
<div class="checkbox-wrapper" #click="check">
<div :class="{ checkbox: true, checked: checked }"></div>
<div class="title"></div>
</div>
</template>
Now you need to declare this Component in same file you declare Vue app, as the following:
Vue.component('my-checkbox', require('path/to/checkboxComponent.vue').default);
In my case
I have three files with these directories structure:
js/app.js
js/components/checkboxComponent.vue
js/components/checkboxComponent.html
In app.js, i'm declare the Vue app, so the require method path need to start with a dot, like this:
Vue.component('my-checkbox', require('./components/checkboxComponent.vue').default);

In Vue, anyway to reference to the element when binding attributes in template?

In template scope, are there variable referencing the element itself like a $this or $el?
Instead of,
<template>
<div #click="$emit('xxx')" :class="{active:mode=='xxx'}" something_for_xxx></div>
<div #click="$emit('yyy')" :class="{active:mode=='yyy'}" something_for_yyy></div>
<div #click="$emit('zzz')" :class="{active:mode=='zzz'}" something_for_zzz></div>
</template>
Can we write something like the following, to avoid forgetting to change one of the mode name?
<template>
<div mode="xxx" #click="$emit($this.mode)" :class="{active:mode==$this.mode}" something_for_xxx></div>
<div mode="yyy" #click="$emit($this.mode)" :class="{active:mode==$this.mode}" something_for_yyy></div>
<div mode="zzz" #click="$emit($this.mode)" :class="{active:mode==$this.mode}" something_for_zzz></div>
</template>
Workaround:
<template>
<div v-for"mode_ in ["xxx"] #click="$emit(mode_)" :class="{active:mode==mode_}" something_for_xxx></div>
<div v-for"mode_ in ["yyy"] #click="$emit(mode_)" :class="{active:mode==mode_}" something_for_yyy></div>
<div v-for"mode_ in ["zzz"] #click="$emit(mode_)" :class="{active:mode==mode_}" something_for_zzz></div>
</template>
In the event handlers, you can always access $event.target to access the element (see https://v2.vuejs.org/v2/guide/events.html#Method-Event-Handlers) but for inline binding (like :class) you cannot because the element has not been rendered yet.
I suggest you change how you cycle through each value
<div v-for="elMode in ['xxx', 'yyy', 'zzz']"
#click="$emit('click', elMode)" :class="{active:mode==elMode}"/>
That is the typical situation where you should build your elements in a v-for loop:
Vue.component('my-component', {
template: '#my-component',
props: {
mode: String,
},
data() {
return {
modes: ['xxx', 'yyy', 'zzz'],
};
},
});
new Vue({
el: '#app',
data: {
mode: 'xxx',
},
methods: {
log(event) {
this.mode = event;
console.log(event);
}
},
});
.active {
color: green;
}
.pointer {
cursor: pointer;
}
<script src="https://unpkg.com/vue#2"></script>
<div id="app">
<my-component
:mode='mode'
#click="log($event)"
></my-component>
</div>
<template id="my-component">
<div>
<div
v-for="currentMode of modes"
#click="$emit('click', currentMode)"
:class="{active:mode==currentMode}"
class="pointer"
>{{currentMode}}</div>
</div>
</template>