Values not reactive once available in Vuex Store - javascript

So I'm retrieving my data from my api using vue-resource which is happening correctly, the state is updated and from the console I am able to see the values I'm requesting. My problem is that when the application loads the data from the store doesn't seem to be impacting the application on load, but if for example I change between pages the information is displayed correctly. This is leading me to believe somewhere along the way I have gotten the life cycle hooks incorrect, or I have handled the state incorrectly inside vuex.
Vuex store
import Vue from 'vue'
import Vuex from 'vuex'
import VueResource from 'vue-resource'
Vue.use(VueResource)
Vue.use(Vuex)
const state = {
twitter: 0,
instagram: 0,
youtube: 0,
twitch: 0
}
const actions = {
LOAD_METRICS: ({commit}) => {
Vue.http.get('http://109.74.195.166:2000/metrics').then(response => {
let out = [{
twitter: Number(response.body[0].twitter),
instagram: Number(response.body[0].instagram),
youtube: Number(response.body[0].youtube),
twitch: Number(response.body[0].twitch)
}]
commit('SET_METRICS', out)
}).catch((e) => {
console.log(e)
})
}
}
const mutations = {
SET_METRICS (state, obj) {
state.twitter = obj[0].twitter
state.instagram = obj[0].instagram
state.youtube = obj[0].youtube
state.twitch = obj[0].twitch
}
}
const getters = {}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
Here I am trying to dispatch an event to gather the needed information using a mutation.
<template>
<div id="app">
<NavigationTop></NavigationTop>
<router-view></router-view>
<SocialBar></SocialBar>
<CopyrightBar></CopyrightBar>
</div>
</template>
<script>
export default {
name: 'app',
ready: function () {
this.$store.dispatch('LOAD_METRICS')
}
}
</script>
<style>
#import url('https://fonts.googleapis.com/css?family=Roboto:400,700,900');
#app {
font-family: 'Roboto', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: white;
background: url('./assets/Images/bodyBackground.jpg');
}
</style>
Then finally I am requesting the information inside of the component to be used by countup.js and also giving it to the method inside data.
<template>
<div class="hero">
<div class="container hero-content">
<div class="row hero-back align-items-end">
<div class="col-lg-6">
<div class="row">
<div class="col-lg-6" v-for="icons in socialIcons">
<Hero-Tile
:name="icons.name"
:icon="icons.iconName"
:count="icons.count"
:numeric="icons.numeric"
></Hero-Tile>
<h1>{{origin}}</h1>
</div>
</div>
</div>
</div>
</div>
<div class="diagonal-left-lines"></div>
<div class="home-hero-img"><img class="img-fluid" src="../../assets/Images/home-hero.jpg"></div>
</div>
</template>
<script>
import HeroTile from './Hero-Tile'
import CountUp from 'countup.js'
export default {
components: {HeroTile},
name: 'hero',
data () {
return {
origin: '',
socialIcons: [
{
name: 'twitter',
iconName: 'twitter',
count: this.$store.state.twitter,
numeric: 26000
},
{
name: 'instagram',
iconName: 'instagram',
count: this.$store.state.instagram,
numeric: 35000
},
{
name: 'youtube',
iconName: 'youtube-play',
count: this.$store.state.youtube,
numeric: 15000
},
{
name: 'twitch',
iconName: 'twitch',
count: this.$store.state.twitch,
numeric: 127000
}
]
}
},
methods: {
updateNumbers: function () {
let options = {
useEasing: true,
useGrouping: true,
separator: ',',
decimal: '.',
prefix: '',
suffix: 'K'
}
function kFormatter (num) {
return num > 999 ? (num / 1000).toFixed(1) : num
}
let twitter = new CountUp('twitter', 0, kFormatter(this.$store.state.twitter), 0, 3, options)
let instagram = new CountUp('instagram', 0, kFormatter(this.$store.state.instagram), 0, 3, options)
let youtube = new CountUp('youtube', 0, kFormatter(this.$store.state.youtube), 0, 3, options)
let twitch = new CountUp('twitch', 0, kFormatter(this.$store.state.twitch), 0, 3, options)
twitter.start()
instagram.start()
youtube.start()
twitch.start()
}
},
mounted: function () {
this.updateNumbers()
}
}
</script>
To be clear at the moment it seems to just load '0k' so it's as if there is some form of race condition occurring causing it not to actually load the information on load-up. Though I'm not sure what the correct approach is here.

This was eventually solved by what I'm going to describe as hacking as I don't actually know the exact correct answer at this time. Though what I have does work.
Points of Interest below:
Store
LOAD_METRICS: ({commit}, context) => {
console.log(context)
if (context === true) {
return new Promise((resolve) => {
resolve('loaded')
})
}
return new Promise((resolve) => {
Vue.http.get('real ip is normally here').then(response => {
let out = {
twitter: Number(response.body[0].twitter),
instagram: Number(response.body[0].instagram),
youtube: Number(response.body[0].youtube),
twitch: Number(response.body[0].twitch),
loaded: false
}
commit('SET_METRICS', out)
resolve(out)
}).catch((e) => {
console.log(e)
})
})
}
In the above I am now sending an instance of the current store.state.metrics.loaded when the dispatch event is sent. Which is then checked to see the truthness of the current value, Because the first load should always return false we then return a promise utilizing an API call while also mutating the store so we have the values from later. Thus onwards because we mutated the loaded event to be true the next further instances shall return a value of true and a new promise will be resolved so we can make sure the .then() handler is present.
Component
created: function () {
this.$store.dispatch('LOAD_METRICS', this.$store.state.metrics.loaded).then((res) => {
if (res !== 'loaded') {
this.updateNumbers(res)
} else {
this.socialIcons[0].count = this.kFormatter(this.$store.state.metrics.twitter) + 'K'
this.socialIcons[1].count = this.kFormatter(this.$store.state.metrics.instagram) + 'K'
this.socialIcons[2].count = this.kFormatter(this.$store.state.metrics.youtube) + 'K'
this.socialIcons[3].count = this.kFormatter(this.$store.state.metrics.twitch) + 'K'
}
})
}
Within our component created life cycle hook we then use the resulting values to identify the path to be taken when the components are created within the DOM again, this time just loading the values and allow normal data binding to update the DOM.
I believe there is a better method of approach then deliberating the logic of the state within the action setter and returning a promise that is essentially redundant other than for ensuring the .then() handle is present.

Related

How can I add action menu in usermenu odoo15

In odoo 15, how can I add new action menu in user menu? In other odoo versions (13 and 14), it was possible by inheriting from UserMenu.Actions.
In odoo 15, I tried the following code but it is not working.
Thanks for any suggestion
/** #odoo-module **/
import { registry } from "#web/core/registry";
import { preferencesItem } from "#web/webclient/user_menu/user_menu_items";
export function UserLog(env) {
return Object.assign(
{},
preferencesItem(env),
{
type: "item",
id: "log",
description: env._t("UserRecent Log"),
callback: async function () {
const actionDescription = await env.services.orm.call("user.recent.log", "action_get");
actionDescription.res_id = env.services.user.userId;
env.services.action.doAction(actionDescription);
},
sequence: 70,
}
);
}
registry.category("user_menuitems").add('profile', UserLog, { force: true })
This is my model code.
class UserRecentLog(models.Model):
_name = 'user.recent.log'
_order = "last_visited_on desc"
#api.model
def action_get(self):
return self.env['ir.actions.act_window']._for_xml_id('user_recent_log.action_user_activity')
This is my xml view.
<!-- actions opening views on models -->
<record model="ir.actions.act_window" id="action_user_activity">
<field name="name">User Recent Log(s)</field>
<field name="res_model">user.recent.log</field>
<field name="view_mode">tree,form</field>
<field name="view_id" ref="user_activity_view_tree"/>
</record>
You don't need to change anything, your code should work. You can check the user preferences menu item in web module (similar to your menu item).
export function preferencesItem(env) {
return {
type: "item",
id: "settings",
description: env._t("Preferences"),
callback: async function () {
const actionDescription = await env.services.orm.call("res.users", "action_get");
actionDescription.res_id = env.services.user.userId;
env.services.action.doAction(actionDescription);
},
sequence: 50,
};
}
registry
.category("user_menuitems")
.add("profile", preferencesItem)
There is another implementation in hr module:
import { registry } from "#web/core/registry";
import { preferencesItem } from "#web/webclient/user_menu/user_menu_items";
export function hrPreferencesItem(env) {
return Object.assign(
{},
preferencesItem(env),
{
description: env._t('My Profile'),
}
);
}
registry.category("user_menuitems").add('profile', hrPreferencesItem, { force: true })
So you can rewrite your code above as following:
import { registry } from "#web/core/registry";
import { preferencesItem } from "#web/webclient/user_menu/user_menu_items";
export function UserLog(env) {
return Object.assign(
{},
preferencesItem(env),
{
type: "item",
id: "log",
description: env._t("Log"),
callback: async function () {
const actionDescription = await env.services.orm.call("res.users.log", "action_user_activity");
env.services.action.doAction(actionDescription);
},
sequence: 70,
}
);
}
registry.category("user_menuitems").add('profile', UserLog, { force: true })
Edit:
The tree view mode is ignored when executing the window action.
The _executeActWindowAction will check for the tree view type in the views registry to construct the views object and unfortunately, the tree view mode was not added to that registry.
To show the tree view, you can add [false, 'list'] to the views list and specify the view type (list) in the doAction options:
actionDescription.views.push([actionDescription.view_id[0], 'list'])
env.services.action.doAction(actionDescription, {viewType: 'list'});
Or update the views list and change tree to list:
actionDescription.views[0][1] = 'list';
Of course , you can do the same in the action_get method:
action = self.env['ir.actions.act_window']._for_xml_id('user_recent_log.action_user_activity')
action['views'][0] = action['view_id'][0], 'list'
return action

Vuejs: Passing SAVE function into CRUD component

I am struggeling with a proper solution which requires an advanced parent-child communication in vuejs. There can be many different parent components which has a logic how to save data. From the other side there will be only one child component which has a list of elements and a form to create new elements but it doesn't know how to save the data.
The question is: Is there any other way (better approach) to have the same functionality but to get rid of this.$refs.child links. For example I am wondering if I can just pass a function (SaveParent1(...) or SaveParent2(...)) to the child component. But the problem is the function contains some parent's variables which won't be available in child context and those variables could be changed during the runtime.
Just few clarifications:
The methods SaveParent1 and SaveParent2 in real life return
Promise (axios).
The child-component is like a CRUD which is used
everywhere else.
At the moment the communication looks like that: CHILD -event-> PARENT -ref-> CHILD.
Bellow is the example:
<div id="app">
<h2>😀Advanced Parent-Child Communication:</h2>
<parent-component1 param1="ABC"></parent-component1>
<parent-component2 param2="XYZ"></parent-component2>
</div>
Vue.component('parent-component1', {
props: { param1: { type: String, required: true } },
methods: {
onChildSubmit(p) {
// Here will be some logic to save the param. Many different parents might have different logic and all of them use the same child component. So child-component contains list, form and validation message but does not know how to save the param to the database.
var error = SaveParent1({ form: { p: p, param1: this.param1 } });
if (error)
this.$refs.child.paramFailed(error);
else
this.$refs.child.paramAdded(p);
}
},
template: `<div class="parent"><p>Here is parent ONE:</p><child-component ref="child" #submit="onChildSubmit"></child-component></div>`
});
Vue.component('parent-component2', {
props: { param2: { type: String, required: true } },
methods: {
onChildSubmit(p) {
// Here is a different logic to save the param. In prictice it is gonna be different requests to the server.
var error = SaveParent2({ form: { p: p, param2: this.param2 } });
if (error)
this.$refs.child.paramFailed(error);
else
this.$refs.child.paramAdded(p);
}
},
template: `<div class="parent"><p>Here is parent TWO:</p><child-component ref="child" #submit="onChildSubmit"></child-component></div>`
});
Vue.component('child-component', {
data() {
return {
currentParam: "",
allParams: [],
errorMessage: ""
}
},
methods: {
submit() {
this.errorMessage = "";
this.$emit('submit', this.currentParam);
},
paramAdded(p) {
this.currentParam = "";
this.allParams.push(p);
},
paramFailed(msg) {
this.errorMessage = msg;
}
},
template: `<div><ol><li v-for="p in allParams">{{p}}</li></ol><label>Add Param: <input v-model="currentParam"></label><button #click="submit" :disabled="!currentParam">Submit</button><p class="error">{{errorMessage}}</p></div>`
});
function SaveParent1(data) {
// Axios API to save data. Bellow is a simulation.
if (Math.random() > 0.5)
return null;
else
return 'Parent1: You are not lucky today';
}
function SaveParent2(data) {
// Axios API to save data. Bellow is a simulation.
if (Math.random() > 0.5)
return null;
else
return 'Parent2: You are not lucky today';
}
new Vue({
el: "#app"
});
There is also a live demo available: https://jsfiddle.net/FairKing/novdmcxp/
Architecturally I recommend having a service that is completely abstract from the component hierarchy and that you can inject and use in each of the components. With this kind of component hierarchy and architecture it is easy to run into these issues. It is important to abstract as much functionality and business logic from the components as possible. I think of components in these modern frameworks just merely as HTML templates on steroids, which should at most act as controllers, keeping them as dumb and as thin as possible so that you don't run into these situations. I do not know vue.js so I cannot give you the technical solution but hope this indication helps
I think I have found a solution. So no two ways communication. I can just pass a method and the child will do everything without communicating with parent. I am happy with that I am marking it as an answer. Thanks everyone for your help.
Let me please know what do you think guys.
Bellow is my solution:
<div id="app">
<h2>😀Advanced Parent-Child Communication:</h2>
<parent-component1 param1="ABC"></parent-component1>
<parent-component2 param2="XYZ"></parent-component2>
</div>
Vue.component('parent-component1', {
props: { param1: { type: String, required: true } },
computed: {
saveFunc() {
return function(p) { SaveParent1({ form: { p: p, param1: this.param1 } }); }.bind(this);
}
},
template: `<div class="parent"><p>Here is parent ONE:</p><child-component :saveFunc="saveFunc"></child-component></div>`
});
Vue.component('parent-component2', {
props: { param2: { type: String, required: true } },
computed: {
saveFunc() {
return function(p) { SaveParent2({ form: { p: p, param2: this.param2 } }); }.bind(this);
}
},
template: `<div class="parent"><p>Here is parent TWO:</p><child-component :saveFunc="saveFunc"></child-component></div>`
});
Vue.component('child-component', {
props: {
saveFunc: { type: Function, required: true }, // This is gonna be a Promise in real life.
},
data() {
return {
currentParam: "",
allParams: [],
errorMessage: ""
}
},
methods: {
submit() {
this.errorMessage = "";
var error = this.saveFunc(this.currentParam);
if (error)
this.paramFailed(error);
else
this.paramAdded(this.currentParam);
},
paramAdded(p) {
this.currentParam = "";
this.allParams.push(p);
},
paramFailed(msg) {
this.errorMessage = msg;
}
},
template: `<div><ol><li v-for="p in allParams">{{p}}</li></ol><label>Add Param: <input v-model="currentParam"></label><button #click="submit" :disabled="!currentParam">Submit</button><p class="error">{{errorMessage}}</p></div>`
});
function SaveParent1(data) {
console.log(data);
// Axios API to save data
if (Math.random() > 0.5)
return null;
else
return 'Parent1: You are not lucky today';
}
function SaveParent2(data) {
console.log(data);
// Axios API to save data
if (Math.random() > 0.5)
return null;
else
return 'Parent2: You are not lucky today';
}
new Vue({
el: "#app"
});
The demo link: https://jsfiddle.net/FairKing/novdmcxp/126/

Next page does not open. Problem with pagination

I need to make a pagination in my task, but it is not working.
I made two buttons to which I attached the "click" event and I registered a property in the "data". When I click on the buttons, the property changes and is written to the link and in the same way changes the current 10 posts to the following.
But for some reason it does not work as it should work. Can someone please explain what my mistake is and if you can suggest some articles on the subject of "pagination".
This is my html:
<button type="button" #click="counter -=1" class="prev">Prev</button>
<div class="counter">{{ counter }}</div>
<button type="button" #click="counter +=1" class="next">Next</button>
This is my Vue:
export default {
name: 'app',
data () {
return {
counter: 1,
zero: 0,
posts: [],
createTitle: '',
createBody: '',
visiblePostID: ''
};
},
created () {
axios.get('http://jsonplaceholder.typicode.com/posts?_start=${this.counter}+${this.zero}&_limit=10').then(response => {
this.posts = response.data;
});
}
};
The created method is called only when the component is created. To make the GET request everytime the counter increase or decrease use watches link.
Your example will become:
export default {
name: 'app',
data () {
return {
counter: 1,
zero: 0,
posts: [],
createTitle: '',
createBody: '',
visiblePostID: '',
}
},
watch: {
counter: function(newValue, oldValue) {
this.getData()
}
}
created(){
this.getData()
},
methods: {
getData() {
axios.get(`http://jsonplaceholder.typicode.com/posts?_start=${this.counter}+${this.zero}&_limit=10`).then(response => {
this.posts = response.data
})
}
}
}
You need to create a watcher for your counter that fires a load method. This way every time your counter changes you'll load in the correct posts for the page in your paginated results.
export default {
name: 'app',
data () {
return{
counter: 1,
...
}
},
created(){
this.loadPosts()
},
watch: {
counter(newVal, oldVal){
this.loadPosts()
}
},
methods: {
loadPosts(){
axios.get('http://jsonplaceholder.typicode.com/posts?_start=${this.counter}+${this.zero}&_limit=10')
.then(response => {
this.posts = response.data
})
}
}
}
Maybe this can help you. https://scotch.io/courses/getting-started-with-vue/vue-events-build-a-counter
I don't know vue, but looks like you need a function to load new data

VueJS / JS DOM Watch / Observer in a multi phase render scenario

Scenario:
I’m developing a Vue scroll component that wraps around a dynamic number of HTML sections and then dynamically builds out vertical page navigation allowing the user to scroll or jump to page locations onScroll.
Detail:
a. In my example my scroll component wraps 3 sections. All section id’s start with "js-page-section-{{index}}"
b. The objective is to get the list of section nodes (above) and then dynamically build out vertical page (nav) navigation based on the n number of nodes found in the query matching selector criteria. Therefore, three sections will result in three page section navigation items. All side navigation start with “js-side-nav-{{index}}>".
c. Once the side navigation is rendered I need to query all the navigation nodes in order to control classes, heights, display, opacity, etc. i.e document.querySelectorAll('*[id^="js-side-nav"]');
EDIT
Based on some research here are the options for my problem. Again my problem being 3 phase DOM state management i.e. STEP 1. Read all nodes equal to x, then STEP 2. Build Side Nav scroll based on n number of nodes in document, and then STEP 3. Read all nav nodes to sync with scroll of document nodes:
Create some sort of event system is $emit() && $on. In my opinion this gets messy very quickly and feels like a poor solution. I found myself quickly jumping to $root
Vuex. but that feels like an overkill
sync. Works but really that is for parent child property state management but that again requires $emit() && $on.
Promise. based service class. This seems like the right solution, but frankly it became a bit of pain managing multiple promises.
I attempted to use Vue $ref but frankly it seems better for managing state rather than multi stage DOM manipulation where a observer event approach is better.
The solution that seems to work is Vues $nextTick(). which seems to be similar to AngularJS $digest. In essence it is a . setTimeout(). type approach just pausing for next digest cycle. That said there is the scenario where the tick doesn’t sync the time requires so I built a throttle method. Below is the code update for what is worth.
The refactored watch with nextTick()
watch: {
'page.sections': {
handler(nodeList, oldNodeList){
if (this.isNodeList(nodeList) && _.size(nodeList) && this.sideNavActive) {
return this.$nextTick(this.sideNavInit);
}
},
deep: true
},
},
The REFACTORED Vue component
<template>
<div v-scroll="handleScroll">
<nav class="nav__wrapper" id="navbar-example">
<ul class="nav">
<li role="presentation"
:id="sideNavPrefix + '-' + (index + 1)"
v-for="(item, key,index) in page.sections">
<a :href="'#' + getAttribute(item,'id')">
<p class="nav__counter" v-text="('0' + (index + 1))"></p>
<h3 class="nav__title" v-text="getAttribute(item,'data-title')"></h3>
<p class="nav__body" v-text="getAttribute(item,'data-body')"></p>
</a>
</li>
</ul>
</nav>
<slot></slot>
</div>
</template>
<script>
import ScrollPageService from '../services/ScrollPageService.js';
const _S = "section", _N = "sidenavs";
export default {
name: "ScrollSection",
props: {
nodeId: {
type: String,
required: true
},
sideNavActive: {
type: Boolean,
default: true,
required: false
},
sideNavPrefix: {
type: String,
default: "js-side-nav",
required: false
},
sideNavClass: {
type: String,
default: "active",
required: false
},
sectionClass: {
type: String,
default: "inview",
required: false
}
},
directives: {
scroll: {
inserted: function (el, binding, vnode) {
let f = function(evt) {
if (binding.value(evt, el)) {
window.removeEventListener('scroll', f);
}
};
window.addEventListener('scroll', f);
}
},
},
data: function () {
return {
scrollService: {},
page: {
sections: {},
sidenavs: {}
}
}
},
methods: {
getAttribute: function(element, key) {
return element.getAttribute(key);
},
updateViewPort: function() {
if (this.scrollService.isInCurrent(window.scrollY)) return;
[this.page.sections, this.page.sidenavs] = this.scrollService.updateNodeList(window.scrollY);
},
handleScroll: function(evt, el) {
if ( !(this.isScrollInstance()) ) {
return this.$nextTick(this.inViewportInit);
}
this.updateViewPort();
},
getNodeList: function(key) {
this.page[key] = this.scrollService.getNodeList(key);
},
isScrollInstance: function() {
return this.scrollService instanceof ScrollPageService;
},
sideNavInit: function() {
if (this.isScrollInstance() && this.scrollService.navInit(this.sideNavPrefix, this.sideNavClass)) this.getNodeList(_N);
},
inViewportInit: function() {
if (!(this.isScrollInstance()) && ((this.scrollService = new ScrollPageService(this.nodeId, this.sectionClass)) instanceof ScrollPageService)) this.getNodeList(_S);
},
isNodeList: function(nodes) {
return NodeList.prototype.isPrototypeOf(nodes);
},
},
watch: {
'page.sections': {
handler(nodeList, oldNodeList){
if (this.isNodeList(nodeList) && _.size(nodeList) && this.sideNavActive) {
return this.$nextTick(this.sideNavInit);
}
},
deep: true
},
},
mounted() {
return this.$nextTick(this.inViewportInit);
},
}
</script>
END EDIT
ORIGINAL POST
Problem & Question:
PROBLEM:
The query of sections and render of navs work fine. However, querying the nav elements fails as the DOM has not completed the render. Therefore, I’m forced to use a setTimeout() function. Even if I use a watch I’m still forced to use timeout.
QUESTION:
Is there a promise or observer in Vue or JS I can use to check to see when the DOM has finished rendering the nav elements so that I can then read them? Example in AngularJS we might use $observe
HTML EXAMPLE
<html>
<head></head>
<body>
<scroll-section>
<div id="js-page-section-1"
data-title="One"
data-body="One Body">
</div>
<div id="js-page-section-2"
data-title="Two"
data-body="Two Body">
</div>
<div id="js-page-section-3"
data-title="Three"
data-body="THree Body">
</div>
</scroll-section>
</body>
</html>
Vue Compenent
<template>
<div v-scroll="handleScroll">
<nav class="nav__wrapper" id="navbar-example">
<ul class="nav">
<li role="presentation"
:id="[idOfSideNav(key)]"
v-for="(item, key,index) in page.sections.items">
<a :href="getId(item)">
<p class="nav__counter">{{key}}</p>
<h3 class="nav__title" v-text="item.getAttribute('data-title')"></h3>
<p class="nav__body" v-text="item.getAttribute('data-body')"></p>
</a>
</li>
</ul>
</nav>
<slot></slot>
</div>
</template>
<script>
export default {
name: "ScrollSection",
directives: {
scroll: {
inserted: function (el, binding, vnode) {
let f = function(evt) {
_.forEach(vnode.context.page.sections.items, function (elem,k) {
if (window.scrollY >= elem.offsetTop && window.scrollY <= (elem.offsetTop + elem.offsetHeight)) {
if (!vnode.context.page.sections.items[k].classList.contains("in-viewport") ) {
vnode.context.page.sections.items[k].classList.add("in-viewport");
}
if (!vnode.context.page.sidenavs.items[k].classList.contains("active") ) {
vnode.context.page.sidenavs.items[k].classList.add("active");
}
} else {
if (elem.classList.contains("in-viewport") ) {
elem.classList.remove("in-viewport");
}
vnode.context.page.sidenavs.items[k].classList.remove("active");
}
});
if (binding.value(evt, el)) {
window.removeEventListener('scroll', f);
}
};
window.addEventListener('scroll', f);
},
},
},
data: function () {
return {
page: {
sections: {},
sidenavs: {}
}
}
},
methods: {
handleScroll: function(evt, el) {
// Remove for brevity
},
idOfSideNav: function(key) {
return "js-side-nav-" + (key+1);
},
classOfSideNav: function(key) {
if (key==="0") {return "active"}
},
elementsOfSideNav:function() {
this.page.sidenavs = document.querySelectorAll('*[id^="js-side-nav"]');
},
elementsOfSections:function() {
this.page.sections = document.querySelectorAll('*[id^="page-section"]');
},
},
watch: {
'page.sections': function (val) {
if (_.has(val,'items') && _.size(val.items)) {
var self = this;
setTimeout(function(){
self.elementsOfSideNavs();
}, 300);
}
}
},
mounted() {
this.elementsOfSections();
},
}
</script>
I hope I can help you with what I'm going to post here. A friend of mine developed a function that we use in several places, and reading your question reminded me of it.
"Is there a promise or observer in Vue or JS I can use to check to see when the DOM has finished rendering the nav elements so that I can then read them?"
I thought about this function (source), here below. It takes a function (observe) and tries to satisfy it a number of times.
I believe you can use it at some point in component creation or page initialization; I admit that I didn't understand your scenario very well. However, some points of your question immediately made me think about this functionality. "...wait for something to happen and then make something else happen."
<> Credits to #Markkop the creator of that snippet/func =)
/**
* Waits for object existence using a function to retrieve its value.
*
* #param { function() : T } getValueFunction
* #param { number } [maxTries=10] - Number of tries before the error catch.
* #param { number } [timeInterval=200] - Time interval between the requests in milis.
* #returns { Promise.<T> } Promise of the checked value.
*/
export function waitForExistence(getValueFunction, maxTries = 10, timeInterval = 200) {
return new Promise((resolve, reject) => {
let tries = 0
const interval = setInterval(() => {
tries += 1
const value = getValueFunction()
if (value) {
clearInterval(interval)
return resolve(value)
}
if (tries >= maxTries) {
clearInterval(interval)
return reject(new Error(`Could not find any value using ${tries} tentatives`))
}
}, timeInterval)
})
}
Example
function getPotatoElement () {
return window.document.querySelector('#potato-scroller')
}
function hasPotatoElement () {
return Boolean(getPotatoElement())
}
// when something load
window.document.addEventListener('load', async () => {
// we try sometimes to check if our element exists
const has = await waitForExistence(hasPotatoElement)
if (has) {
// and if it exists, we do this
doThingThatNeedPotato()
}
// or you could use a promise chain
waitForExistence(hasPotatoElement)
.then(returnFromWaitedFunction => { /* hasPotatoElement */
if (has) {
doThingThatNeedPotato(getPotatoElement())
}
})
})

Vue.js component model update

Im absolutely new in Vue framework and I need create reusable component with live BTC/LTC/XRP price
For live prices Im using Bitstamp websockets API. Here is example usage with jQuery - run this snippet, is really live.
var bitstamp = new Pusher('de504dc5763aeef9ff52')
var channel = bitstamp.subscribe('live_trades')
channel.bind('trade', function (lastTrade) {
$('p').text(lastTrade.price)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pusher/4.1.0/pusher.min.js"></script>
<h3>BTC/USD price</h3>
<p>loading...</p>
As you can see, its really simple. But, I need to use Vue.js component. So I created this, and its also fully functional:
var bitstamp = new Pusher('de504dc5763aeef9ff52')
Vue.component('live-price', {
template: '<div>{{price}}</div>',
data: function () {
return {
price: 'loading...'
}
},
created: function () {
this.update(this)
},
methods: {
update: function (current) {
var pair = current.$attrs.pair === 'btcusd'
? 'live_trades'
: 'live_trades_' + current.$attrs.pair
var channel = bitstamp.subscribe(pair)
channel.bind('trade', function (lastTrade) {
current.price = lastTrade.price
})
}
}
})
new Vue({
el: '.prices'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/pusher/4.1.0/pusher.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.1/vue.min.js"></script>
<section class="prices">
<live-price pair="btcusd"></live-price>
<live-price pair="ltcusd"></live-price>
<live-price pair="xrpusd"></live-price>
</section>
But, there is big BUT. Am I using Vue right way? WHERE IS IDEAL PLACE to run Pusher? In "created" or "mounted" method? In "computed"? In "watch"? Or where? Am i doing it right? I really dont known, I started with Vue ... today :(
Looks pretty good for your first day using Vue! I would just make a few changes.
The component is reaching out and using a global, bitstamp. Generally with components, you want them to be independent, and not reaching out of themselves to get values. To that end, declare the socket as a property that can be passed in to the component.
Likewise, the pair is passed in as a property, but you do not declare it and instead, use current.$attrs.pair to get the pair. But that's not very declarative and makes it harder for anyone else to use the component. Moreover, by making it a property, you can reference it using this.pair.
When using something like a socket, you should always remember to clean up when you are done using it. In the code below, I added the unsubscribe method to do so. beforeDestroy is a typical lifecycle hook to handle these kinds of things.
Computed properties are useful for calculating values that are derived from your components data: the channel you are subscribing to is a computed property. You don't really need to do this, but its generally good practice.
A Vue can only bind to a single DOM element. You are using a class .prices which works in this case because there is only one element with that class, but could be misleading down the road.
Finally, created is an excellent place to initiate your subscription.
console.clear()
var bitstamp = new Pusher('de504dc5763aeef9ff52')
Vue.component('live-price', {
props:["pair", "socket"],
template: '<div>{{price}}</div>',
data() {
return {
price: 'loading...',
subscription: null
}
},
created() {
this.subscribe()
},
beforeDestroy(){
this.unsubscribe()
},
computed:{
channel(){
if (this.pair === 'btcusd')
return 'live_trades'
else
return 'live_trades_' + this.pair
}
},
methods: {
onTrade(lastTrade){
this.price = lastTrade.price
},
subscribe() {
this.subscription = this.socket.subscribe(this.channel)
this.subscription.bind('trade', this.onTrade)
},
unsubscribe(){
this.subscription.unbind('trade', this.onTrade)
this.socket.unsubscribe(this.channel)
}
}
})
new Vue({
el: '#prices',
data:{
socket: bitstamp
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/pusher/4.1.0/pusher.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.1/vue.min.js"></script>
<section id="prices">
<live-price pair="btcusd" :socket="bitstamp"></live-price>
<live-price pair="ltcusd" :socket="bitstamp"></live-price>
<live-price pair="xrpusd" :socket="bitstamp"></live-price>
</section>
Rewrited - is it ok now?
var config = {
key: 'de504dc5763aeef9ff52'
}
var store = new Vuex.Store({
state: {
pusher: null
},
mutations: {
initPusher (state, payload) {
state.pusher = new Pusher(payload.key)
}
}
})
var livePrice = {
template: '#live-price',
props: ['pair'],
data () {
return {
price: 'loading...',
subscription: null
}
},
computed: {
channel () {
return this.pair === 'btcusd'
? 'live_trades'
: 'live_trades_' + this.pair
}
},
methods: {
onTrade (lastTrade) {
this.price = lastTrade.price
},
subscribe () {
this.subscription = this.$store.state.pusher.subscribe(this.channel)
this.subscription.bind('trade', this.onTrade)
},
unsubscribe () {
this.subscription.unbind('trade', this.onTrade)
this.$store.state.pusher.unsubscribe(this.channel)
}
},
created () {
this.subscribe()
},
beforeDestroy () {
this.unsubscribe()
}
}
new Vue({
el: '#prices',
store,
components: {
'live-price': livePrice
},
created () {
store.commit({
type: 'initPusher',
key: config.key
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/pusher/4.1.0/pusher.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.1/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.3.1/vuex.min.js"></script>
<section id="prices">
<live-price pair="btcusd"></live-price>
<live-price pair="ltcusd"></live-price>
<live-price pair="xrpusd"></live-price>
</section>
<template id="live-price">
<div>
{{price}}
</div>
</template>

Categories

Resources