Vue.js Dynamic Image paths after compiling/runtime - javascript

I am having a problem setting dynamic image paths with Vue.js. I am using the Vue-Cli to build the project.
I believe the issue is caused because I am referencing image paths dynamically after runtime. Normally it seems the references to my ./assets/ folder are converted into ./img/ after runtime. Since I am changing the url dynamically after load the paths don't appear to work/load. Country is initially set via a store getters but is then v-modeled from a language select dropdown, where the values correspond the the url suffix.
<div id="flag-container" :style="{ backgroundImage: `url(${src})` }"></div>
computed: {
src(){
return `./assets/flags/flag-${this.country}.png`;
}
},
data() {
return {
country: this.$store.getters.language
}
}
Inspector shows url change is implemented.
Any recommendation on the best solution for this?

Using webpack require context and beforeMount, I was able to store the images in base64 format inside an object. I stored the object and accessed it with a dynamic key. Thanks Max for leading me to the right documentation.
export default {
beforeMount() {
var that = this;
function importAll(r) {
r.keys().forEach((key) => (that.imgCache[key] = r(key)));
}
importAll(require.context("../assets/flags/", true, /\.png$/));
},
computed: {
src() {
var key = `./flag-${this.country}.png`,
url = this.imgCache[key];
return url;
},
},
};

Don't use
data() {
return {
country: this.$store.getters.language
}
}
as it will stop being reactive to store changes. Use computed property
<div id="flag-container" :style="{ backgroundImage: `url(${src})` }"></div>
computed: {
src(){
return `./assets/flags/flag-${this.country}.png`;
},
country() {
return this.$store.getters.language
}
},

Related

VUE: How to make auto import all images from folder?

i trying auto import all images from folder. Under // tested is what i tried:
<template>
<p>classical art</p>
<img v-for="image in images" :key="image" :src="image.url" :alt="image.alt" />
</template>
<script>
export default {
data: function () {
return {
name: "classical-art",
images: [
{ url: require("../assets/images/classical-art/img-00001.jpg"), alt: "prvnĂ­" },
{ url: require("../assets/images/classical-art/img-00002.jpg"), alt: "druhĂ˝" },
],
};
},
};
// tested
const classicalArt = require(`../assets/images/classical-art/.jpg`)
classicalArt.forEach((image) => {
return image;
});
</script>
<style module lang="scss"></style>
Im not good in this things so i will need a help with this. Probably im just stupid, but i cant make it works. If possible, i want it async (lazy) or whatever it is.
----- UPDATE:
I tried something like that, but still nothing, but with require.context i should be able do this probably:
<template>
<p>classical art</p>
<img :src="getImgUrl()" v-bind:alt="req" />
</template>
<script>
export default {
data: function () {
return {
name: "classical-art",
};
},
methods: {
getImgUrl() {
var req = require.context(
"../assets/images/classical-art/",
false,
/\*.jpg$/
);
req.keys().forEach(function (key) {
req(key);
});
},
},
};
</script>
<style module lang="scss"></style>
I want when I add another image to the classical-art folder to create a new tag automatically and display the image without having to edit the code and manually register it
Can anyone help me with this?
For image rendering you must indicate the exact url to every image, so you have to type every url manually in the correct way.
BTW, your idea can be implemented with NodeJS. Node runtime has access to the file system, so url string can be created authomatically for every file.
Vue, unfortunately, has no real access to your files, it means every your component, file or image must be imported manually.

Spaces are not recognized correctly in the TipTap Editor

we use the rich text editor of TipTap in our project.
But we have the problem, that spaces are not recognized correctly and only after every 2 click a space is created. As framework we use Vue.JS.
import { Editor, EditorContent, EditorMenuBar } from 'tiptap'
import {
HardBreak,
Heading,
OrderedList,
BulletList,
ListItem,
Bold,
Italic,
History
} from 'tiptap-extensions'
import EditorMenuButton from './EditorMenuButton.vue'
export default {
name: 'editor',
components: {
EditorMenuButton,
EditorMenuBar,
EditorContent
},
props: {
value: {
type: null,
default: ' '
}
},
data () {
return {
innerValue: ' ',
editor: new Editor({
extensions: [
new HardBreak(),
new Heading({ levels: [1, 2, 3] }),
new BulletList(),
new OrderedList(),
new ListItem(),
new Bold(),
new Italic(),
new History()
],
content: `${this.innerValue}`,
onUpdate: ({ getHTML }) => {
this.innerValue = getHTML()
}
})
}
},
watch: {
// Handles internal model changes.
innerValue (newVal) {
this.$emit('input', newVal)
},
// Handles external model changes.
value (newVal) {
this.innerValue = newVal
this.editor.setContent(this.innerValue)
}
},
mounted () {
if (this.value) {
this.innerValue = this.value
this.editor.setContent(this.innerValue)
}
},
beforeDestroy () {
this.editor.destroy()
}
}
</script>
does anyone have any idea what could be the reason for assuming only every two spaces?
We had the same problem, we kept the onUpdate trigger but changed the watch so that it would only invoke editor.setContent when the value was actually different.
watch: {
value() {
let html = this.editor.getHTML();
if (html !== this.value) {
this.editor.setContent(this.value);
}
},
},
"Okay the problem is that the watcher will get fired when you type in the editor. So this will check if the editor has focus an will only update the editor content if that's not the case."
watch: {
value(val) {
if (!this.editor.focused) {
this.editor.setContent(val, false);
}
}
},
issue: https://github.com/ueberdosis/tiptap/issues/776#issuecomment-667077233
This bug for me was caused by doing something like this:
watch: {
value: {
immediate: true,
handler(newValue) {
this.editor.setContent(newValue)
},
},
},
Removed this entirely and the bug went away. Maybe this will help someone in future.
Remove onUpdate section and the bug will disapear. I don't know why, but it's interesting to know how to reproduce the bug.
That does help. Following this advice, I am currently using the onBlur event instead of onUpdate, while obtaining the content's HTML using the editor instance and the getHTML() function, as such: this.editor.getHTML().
(In my case I $emit this value in order for it to be reactive to my parent component, but that may be irrelevant for the original question).
Maybe you should try this.
watch: {
// Handles external model changes.
value (newVal) {
// convert whitespace into \u00a0 ->
let content = newVal.replace(/\s/g, "\u00a0");
this.editor.setContent(content)
}
},
It seems like the normal white space has been removed by html automatically. Therefore, I convert whitespace into 'nbsp;' and it's worked.
The code you provided seems to be working just fine. So the issue most likely is produced by a side effect in either your code or some dependency.
To debug this issue you could look for event listeners, especially regarding key press or key down events and looking if you are checking for space key specifically somewhere (event.keyCode === 32 or event.key === " "). In conjunction with event.preventDefault this could explain such an issue.
Another more broad way to debug this is to strip away parts from your code until the bug disappears or add to a minimal example until the bug appears.
Remove onUpdate section and the bug will disapear. I don't know why, but it's interessing to know how to reproduce the bug.
However if you create a "minimal reproductible example" the bug does not appear.
So what ? I don't know.
I found a workaround which is to use vuex.
Rather than assign the value returned by getHTML() in the innerValue variable and then issue an 'input' event, I put this value in the store.

How to copy value from Vuex's state to Data without changing the Vuex's state when the copied Data get changed?

I'm trying to edit a form. So I'm using Vuex to store my form information, and the form itself is inside a vuetify dialog inside a child component. I also use props to cue vuetify dialog to open while also sending an index too.
I set the edit vue data (tableUsulanTemp) with the value of vuex getters (tableUsulan) like so:
props: {
value: false,
index: null
},
model: {
prop: "value",
event: "editClicked"
},
// set vue data with vuex getters
watch:{
value:function(value){
if(value){
this.tableUsulanTemp = this.tableUsulan[this.$props.index];
}else{
this.tableUsulanTemp = {};
}
}
},
computed: {
//here is the vuex getters
...mapGetters(["tableUsulan"]),
editOverlay: {
get: function() {
console.log(this.value);
return this.value;
},
set: function(value) {
console.log("edit button clicked");
this.$emit("editClicked", value);
}
}
},
data() {
return {
// here is vue data where i put the getters to
tableUsulanTemp:{},
};
},
the markup:
<v-text-field
label="Name"
v-model="tableUsulanTemp.name"
>
then when user discard the changes by clicking the discard button, it will set the dialog to false which trigger watcher (look at above code) to reset my edit form data to empty object.
discard(){
this.editOverlay = false;
}
but the problem is the data is not discarded instead it changed. I set user to change the information in the vue data but it seems it also changing in the vuex. so i guess it linked now? so how can i get it unlinked? how can i get vuex state into a vue data without changing the vuex when the vue data get changed?
So the solution is to parse the object to json and back
this.tableUsulanTemp = JSON.parse(JSON.stringify(this.tableUsulan));
here is the detail

Working with Vuex with Vue and displaying data

This is kind of a long explanation of an issue that I'm having on a personal project. Basically, I want to set a data property before my page loads when I read in data from a CSV file using D3.JS. I almost have it done but running into a small issue. Please read on to get more detail.
Basically, when the user comes to a page in my application, I want to display weather graphs. Like I said, I'm using D3.js to read in the data and created an action to do that. It works perfectly fine-I can console.log the data and I know its been read. However, in my vue instance I have a data property, which would hold the data set like this:
data() {
return {
name: this.$store.state.name
weatherData: this.$store.state.yearData
}
}
I then want to ensure that the weatherData is filled, with data from the csv file so I display it on the page like this:
<p>{{ weatherData }}</p>
Nothing special here. When the page loads, weatherData is blank. But I have a beforeMount life cycle hook and if I comment out the only line in it then it will display the data. If I then refresh the page, fire the action to get the data and then uncomment out the line in the beforeMount hook then the data appears! So before I continue this is my full code for the store:
export const store = new Vuex.Store({
state: {
name: 'Weather Data'
yearData: []
},
getters: {
},
mutations: {
setYearData(state, data) {
state.yearData = data
}
},
actions: {
getYearData: ({commit}) => {
d3.csv("../src/components/data/alaska.csv")
.then(function(data){
let yearData = []
for (let i = 0; i < data.length; i++){
let day = data[i].AKST
yearData.push(day)
}
//console.log(yearData)
commit('setYearData', yearData)
})
}
})
Here are parts of the vue file: The template:
<p>{{ weatherData }}</p>
The Vue Intance:
export default {
name: 'Weather',
data() {
return {
name: this.$store.state.name,
weatherData: this.$store.state.yearData
}
},
methods: {
...mapActions([
'getYearData'
])
},
beforeMount(){
this.$store.dispatch('getYearData') //(un)Commenting out this line will make my data appear
}
}
Page when it loads: Notice empty array:
Then either comment out or comment the one line in the beforeMount hook and get this: THE DATA!!!
Again, my end goal is to have the action called and the data set before the page finishes loading. Finally, I know that I don't need VUEX but this project is further helping me understand it. Any guidance on why this is happening would be great.
use mapState instead of putting your data in the data object, which sometimes being late on updating the template.
just make your Vue instance to look like:
import {mapState} from 'vuex'
export default {
name: 'Weather',
data() {
return { }
},
computed:{
...mapState({
name: state=>state.name,
weatherData: state=>state.yearData
})
},
methods: {
...mapActions([
'getYearData'
])
},
beforeMount(){
this.$store.dispatch('getYearData') //(un)Commenting out this line will make my data appear
}
thats way, you work directly with one source of truth-the store, and your name and weatherData will be reactive as well.
more about mapState here: https://vuex.vuejs.org/guide/state.html#the-mapstate-helper

rendering vue.js components and passing in data

I'm having trouble figuring out how to render a parent component, display a list of contracts in a list on part of the page, and when a user clicks on one of them, display the details of that specific contract on the other part of the page.
Here is my slim file:
#contracts_area
.filter-section
ul
li.filter-item v-for="contract in contractsAry" :key="contract.id" #click="showContract(contract)"
| {{ contract.name }}
.display-section
component :is="currentView" transition="fade" transition-mode="out-in"
script type="text/x-template" id="manage-contracts-template"
div
h1 Blank when page is newly loaded for now
script type="text/x-template" id="view-contract-template"
div :apply_contract="showContract"
h1#display-item__name v-name="name"
javascript:
Vue.component('manage-template', {
template: '#manage-contracts-template'
});
Vue.component('view-contract', {
template: '#view-contract-template',
props: ['show_contract'],
data: function() {
return {
name: ''
}
},
methods: {
showContract: function(contract) {
return this.name = contract.name
}
}
});
Vue.http.headers.common['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr('content');
var contractsResource = Vue.resource('/all_contracts{/id}.json');
var contracts = new Vue({
el: '#contracts_area',
data: {
currentView: 'manage-template',
contractsAry: [],
errors: {}
},
mounted: function() {
var that = this;
contractsResource.get().then(
function(res) {
that.contractsAry = res.data;
}
)
},
methods: {
showContract: function(contract) {
this.currentView = 'view-contract'
}
}
});
Basically I'd like it so that when a user clicks on any contract item in the .filter-section, it shows the data for that contract in the .display-section. How can I achieve this?
In short you can bind a value to a prop.
.display-section
component :is="currentView" :contract="currentContract"
view-contract
props: ['contract']
contracts-area
data: {
currentContract: null,
},
methods: {
showContract: function(contract) {
this.currentView = "view-contract";
this.currentContract = contract;
}
}
There are multiple ways to pass data in Vue.
Binding values to props.
Using ref to directly call a method from a child component.
Custom Events. Note that to pass events globally, you will need a global event bus.
A single central source of truth (i.e. vuex)
I have illustrated methods 1, 2, 3 in Codepen
Note that 2nd and 3rd methods will only work after your component has been rendered. In your case, since your components for currentView are dynamic and when user clicked, display-section component does not yet exists; it will not receive any events yet. So their content will be empty at first.
To workaround this you can directly access $parent in mounted() from child component, however this would create coupling between them. Another solution is creating the components but conditionally displaying them. And one another solution would be waiting until child component has been mounted and then emitting events.
If your needs are simple I suggest binding values to props (1), else you may consider using something like vuex.

Categories

Resources