VueJS: v-model on <span> element ? How to handle that? - vue.js

I have this simple component displaying user info:
<div class="m-card-user__details">
<span class="m-card-user__name m--font-weight-500">
{{ firstname }} {{ lastname }}
</span>
<a class="m-card-user__email m--font-weight-300 m-link">
{{ loginEmail }}
</a>
</div>
Script
<script>
export default {
data () {
return {
loginEmail : this.$store.getters.user.loginEmail,
firstname: this.$store.getters.user.firstName,
lastname: this.$store.getters.user.lastName,
}
}
};
</script>
Problem is that if another component change the value of the firstname property in the VueX store, I see that the value is well updated on the store but not on my component here..
How can i set the 2 ways bindings on a element ?

Attaching a store variable directly to data() will break the 2-way-binding.
Use a computed property for that, like:
computed: {
loginEmail() {
return this.$store.getters.user.loginEmail;
}
}
and then use the computed on the span, like {{ loginEmail }}, as you would normally.
Improvement: If you want, you can return the entire ...getters.user (as a object) with
computed, like:
computed: {
user() {
return this.$store.getters.user;
}
}
and then use it on your span like {{ user.loginEmail }} and so on.
This will save you some lines, increase readability and possibly a tiny bit of performance.

You can also directly use $store in your template.
<div class="m-card-user__details">
<span class="m-card-user__name m--font-weight-500">
{{ $store.getters.user.firstName }} {{ $store.getters.user.lastName }}
</span>
<a class="m-card-user__email m--font-weight-300 m-link">
{{ $store.getters.user.loginEmail }}
</a>
</div>
I haven't tried if this works with getters, but I don't see a reason why it wouldn't. Now you could maybe argue it's an anti-pattern, but I'd prefer it over having a computed property solely for this purpose.
See also https://github.com/vuejs/vuex/issues/306.
Edit: Because you mention 2-way binding: You shouldn't do this to update the $store, use actions and mutations instead. In this case, it's fine as it's essentially a 1-way binding where the state flows to the innerHTML of your <span>s.

Related

Access current component data from within slot template

I have the following vue component
<template>
<CardGroup>
<template #headerRight>
<div>Total items: {{ this.total }}</div>
</template>
</CardGroup>
</template>
export default {
data() {
return {
total: 0
};
}
}
I don't understand the scoping problem. The this in the slot template is null and I cannot access the this.total data property. I can use that property outside the slot template though.
Why this is null inside the slot template?
Vue binds properties automatically, please go through it.
data binding
<div>Total items: {{ total }}</div>
Well, the solution was somewhat simple. I just had to omit this
<div>Total items: {{ total }}</div>
It turns out vue binds properties automatically to the _vm.

Vue - v-for with modifying values

Template:
<template>
<nav>
<router-link :to="key" v-for="(value, key) in state.menu" :key="key">{{value}} | </router-link>
</nav>
</template>
Code:
export default {
setup() {
const menu = ['home', 'news', 'about'];
const state = reactive({
menu: {}
});
menu.map(item => {
state.menu[item] = Common.locs[item];
});
return {
Common,
state,
}
}
}
I want to update
:to="key"
to run it through some filter or function to modify it to add the prefix something like "/other/", so instead of rendered
<a href="/home" ...>
I would have
<a href="/other/home" ... >
(Of course, const menu values are mocked for the sake of example; those are fetched from the service so I have no saying in that, and I don't want to modify them after fetching for other reasons)
So in general, my question is not regarding proper routing, but how do you modify v-for data (in my case: key) in the runtime if you need to?
(I guess I could modify mapping line into
state.menu["/other/" + item] = Common.locs[item];
but I want to preserve state.menu as I wrote. I want change to happen during the v-for rendering.)
Have you tried the template literal:
<template>
<nav>
<router-link :to="`/other/${key}`" v-for="(value, key) in state.menu" :key="key">{{value}} | </router-link>
</nav>
</template>

What is the Vue equivalent to Angular's "::" one-time binding?

I saw that mixins are a possibility but not only is it overly verbose and clunky to achieve the desired functionality, it'd be super convenient to have a "::" equivalent that is written in the view/template code.
<template>
<div>
<div>I am a dynamic/observed binding: {{ integerCounter }}</div>
<div>I am a one-time binding: {{ ::integerCounter }}</div>
<button #click="integerCounter += 1">Increment</button>
</div>
</template>
In the above snippet, assuming integerCounter is instantiated at 0, the one-time binding will display "0" even if the button is clicked. The dynamic one will update on render.
Does such a thing exist?
Excellent example illustrating what you're after but I'm afraid Vue doesn't have anything like this that I'm aware of.
The general advice would be to use two explicit data properties. One could even be a prop which initialises the local copy
<template>
<div>I am a dynamic/observed binding: {{ counter }}</div>
<div>I am a one-time binding: {{ initialCounter }}</div>
<button #click="counter++">Increment</button>
</template>
<script>
export default {
props: {
initialCounter: {
type: Number,
default: 0
}
},
data: ({ initialCounter }) => ({
counter: initialCounter
})
}
</script>

VueJS making API calls for every item in v-for and returning them to the right position

Thank you in advance.
So I am fetching list of blog categories via API and rendering it in a list using v-for.
I also need to fetch the amount of blogs in every category and place them beside the category.
But the issue is I am calling a method that calls the api.
<li v-for="item in sidebar" :key="item.identifier">
<nuxt-link
tag="a"
:to="{
name: 'blog-page',
query: { category: item.identifier }
}"
>{{ $localize(item.translations).title }}
{{ getBlogCount(item.identifier) }}
</nuxt-link>
</li>
You know what it shows already example is Animals [Object Promise]
methods: {
async getBlogCount(identifier) {
axios
.get(
"https://example.com/posts?fields=created_at&filter[category.category_id.identifier]=" +
identifier +
"&meta=*"
)
.then(count => {
return count.data.meta.result_count;
});
}
}
What is the best way to handle this kinda thing?
You better call async methods in mounted or created hooks, and set the result to data, and then, use that data in template.
I'd suggest handling this in Script, instead of HTML Template.
What you can do is, depending on when the sidebar is initialized (maybe in the mounted hook), call getBlogCount method to fetch blog counts for each item in sidebar and store that may be in an array or object (or as a separate key-value pair to that same sidebar item object) and then use that data structure to display count values in the template.
Assuming the sidebar is populated in mounted hook and that it's an array of objects, you can do the following:
<template>
<li v-for="item in sidebar" :key="item.identifier">
<nuxt-link
tag="a"
:to="{
name: 'blog-page',
query: { category: item.identifier }
}"
>{{ $localize(item.translations).title }}
{{ item.blogCount }}
</nuxt-link>
</li>
</template>
<script>
mounted () {
// after the sidebar is populated
this.sidebar = this.sidebar.map(async item => {
item.blogCount = await this.getBlogCount(item.identifier)
return item
})
}
</script>
Hope this helps you out

Getting ref of component in async v-for

I have a list of items that don't get created until after an async call happens. I need to be able to get the getBoundingClientRect() of the first (or any) of the created items.
Take this code for instance:
<template>
<div v-if="loaded">
<div ref="myItems">
<div v-for="item in items">
<div>{{ item.name }}</div>
</div>
</div>
</div>
<div v-else>
Loading...
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
items: []
}
},
created() {
axios.get('/url/with/some/data.json').then((response) => {
this.items = response.data;
this.loaded = true;
}, (error) => {
console.log('unable to load items');
});
},
mounted() {
// $refs is empty here
console.log(this.$refs);
// this.$refs.myItems is undefined
}
};
</script>
So, I'm trying to access the myItems ref in the mounted() method, but the this.$refs is empty {} at this point. So, therefore, I tried using a component watch, and various other methods to determine when I can read the ref value, but have been unsuccessful.
Anyone able to lead me in the right direction?
As always, thanks again!!
UPDATES
Added a this.$watch in the mounted() method and the $refs still come back as {}. I then added the updated() method to the code, then was able to access $refs there and it seemed to work. But, I don't know if this is the correct solution?
How does vuejs normally handle something like dynamically moving a div to an on-screen position based on async data? This is similar to what I'm trying to do, grab an element on screen once it has been rendered first (if it even should be rendered at all based on the async data), then access it to do something with it (move it to a position)?
Instead of doing on this.$refs.myItems during mounted, you can do it after the axios promise returns the the response.
you also update items and loaded, sou if you want to use watch, you can use those
A little late, maybe it helps someone.
The problem is, you're using v-if, which means the element with ref="myItems" doesn't exist yet. In your code this only happens when Axios resolves i.e. this.loaded.
A better approach would be to use a v-show.
<template>
<div>
<div v-show="loaded">
<div ref="myItems">
<div v-if="loaded">
<div v-for="item in items">
<div>{{ item.name }}</div>
</div>
</div>
</div>
</div>
<div v-show="!loaded">
Loading...
</div>
</div>
</template>
The difference is that an element with v-show will always be rendered and remain in the DOM; v-show only toggles the display CSS property of the element.
https://v2.vuejs.org/v2/guide/conditional.html#v-show