Nuxt add parameters without page and without reload the page - vue.js

I have a page with big list of data and some buttons for filtering.
for example 2 buttons to filter by status:
Complete status
Cancel status
I want when the user clicked on the complete the url to be changed to
http://demo.com/list?filter=complete
the page does not reloading, it just for get specific url foreach filter button.
How can I implement the code in Nuxt application?

You cannot use $route or $router to change url, it set a new html5 history state and reload the page. So, to change url without reloading, history.replaceState do the job. In your page or component:
methods: {
onClickComplete() {
if (!process.server) { // I'm not sure it's necessary
history.replaceState({}, null, window.location + '?filter=complete') // or use your own application logic: globalSiteUrl, $route... or queryString some vars...
}
}
}

At first you should change your route with "$route.push" or click on
these ways change the route without reloading
After than you can use "pages watchquery" to handle event of changing route
https://nuxtjs.org/api/pages-watchquery/

first create this helper function
export function getAbsoluteUrl(to) {
const path = $nuxt.$router.resolve(to).href
return window.location.origin + path
}
this is example for my tabs
watch: {
tab(value) {
if (!process.server) {
const url = getAbsoluteUrl({
params: { ...this.$route.params, activeTab: value }
})
history.replaceState({}, null, url) // or use your own application logic: globalSiteUrl, $route... or queryString some vars...
}
}
},

Related

Upload image need to refresh using $emit / $on in Vue

I have a method that calls the user data via axios
// method name getUser()
const user = await axios.get(`/user/${this.id}`)
this.id = user.data.data.id
this.name = user.data.data.name
this.email = user.data.data.email
I then use that in the mounted so if user visits /profile/id
it'll load the user data
mounted() {
this.getUser()
}
I tried to upload an image and I emit the event using global event bus once the image is successfully uploaded.
this.$event.$emit('IMAGE_UPLOAD')
Then catch that on the mounted too
mounted () {
// if I remove this it works, but I need to preload the data of the user
this.getUser()
this.$event.$on('IMAGE_UPLOAD', () => {
this.getUser()
})
}
my problem is it doesn't change the image meaning I still need to refresh the page if I call the this.getUser() too inside the mounted.
So I'm wondering how to work around this.
Thanks!
Since the url and name of the image does not change when the new image is uploaded the image in the browser is not updated. So what I have done in the past is a little trick to essentially change the url to the image by adding a unique query parameter. So use a data property for the location of your user image and in your method where you update the users data also update the img url and add something unique to the query parameter. I usually use new Date().getTime(). So you will end up with something like /img/user-xxxx.png?1559289852686
data(){
userImg: '/img/user-xxxx.png'
},
methods:{
getUser(){
//... get your user data
.then((data)=>{
this.userImg = data.user.img +'?'+ new Date().getTime();
})
}

How to get ID of Tab of exist url

i want to get ID of Tab of exist url
For exemple i have 3 tabs in chrome
tab 1 is youtube
tab 2 is google
tab 3 is twitter
and i want get id of tab already existed url google com
Here is an example:
// get all the tabs, you can also limit it to the current window if you wish
// chrome.tabs.query({currentWindow: true}, ...)
chrome.tabs.query({}, tabs => {
// loop through the tabs
for (const tab of tabs) {
if (tab.url === 'theOneYouWant) {
// do whatever needed with tab.id
// break/stop the loop
break;
}
}
});
You can change the code to to check for the domain (not the whole URL) or any other relevant criteria.
Use chrome.tabs API in your extension page such as the browserAction popup or the background script.
manifest.json:
"permissions": ["tabs"]
Simplest case - no variations in domain name:
chrome.tabs.query({url: 'https://www.youtube.com/*'}, tabs => {
// use 'tabs' inside the callback
});
Simple case - variations in sub-domain but the TLD (top level domain) name doesn't have variations:
chrome.tabs.query({url: 'https://*.twitter.com/*'}, tabs => {
// use 'tabs' inside the callback
});
Tough case - TLD varies:
const RE_ALL_GOOGLE = /^https:\/\/(www\.)?google\.([a-z]{2,3}|com?\.[a-z]{2})\//;
// the tabs API doesn't accept wildcards in TLD so we need to enumerate all tabs
// and we restrict the list to https-only as an optimization for the case of many open tabs
chrome.tabs.query({url: 'https://*/*'}, tabs => {
const googleTabs = tabs.filter(({url}) => RE_ALL_GOOGLE.test(url));
// use 'googleTabs' here inside the callback
});
You can write a more restrictive regexp by using the full list of all Google domains and a RegExp generator like this one.
Content scripts can't use chrome.tabs directly so you'll need to do it via a background script.
content script:
chrome.runtime.sendMessage({
action: 'getTabs',
url: 'https://*/*',
// messaging can't transfer regexps so we convert it to a string
pattern: /^https:\/\/(www\.)?google\.([a-z]{2,3}|com?\.[a-z]{2})\//.source,
}, tabs => {
// use 'tabs' inside the callback
});
manifest.json:
"permissions": ["tabs"],
"background": {
"scripts": ["background.js"],
"persistent": false
}
background.js:
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.action === 'getTabs') {
chrome.tabs.query({url: msg.url}, tabs => {
if (msg.pattern) {
const re = new RegExp(msg.pattern);
tabs = tabs.filter(({url}) => re.test(url));
}
sendResponse(tabs);
});
// keep the reponse channel open since the chrome.tabs API is asynchronous
return true;
}
});

Load component/template depending on the route param vuejs

I would like to ask if can I implement this on vuejs, so basically the code will load a page/template base on the param url. I've been searching for a while and can't get the results I need or maybe I'm just searching a wrong keyword.
My url is like this, so I just can't manually declare the url in my route because it is dynamic, fetch from the database.
path: '/user/page_type
Thank you very much!
export default {
mounted () {
if(this.$routes.params.page_type == "home"){
// Load Homepage Here
// ../../../page/HomePage.vue
}
else if(this.$routes.params.page_type == "speaker"){
// Load Speakerpage Here
// ../../../page/HomePage.vue
}
else if(this.$routes.params.page_type == 'html'){
// Load HTML Page Here
// ../../../page/HtmlPage.vue
}
}
}
This is available out of the box within official addon vue-router.
Docs for your case: link

Riot JS unmount all tags in a page and then mount only one tag is not working

I am using Riot JS and in my index.html, I have 3 custom tags - header, login-panel and candidates-panel inside my body. In my main app.js, in the callback function of $(document).ready, I execute the current route and also register a route change handler function. In my switchView, I unmount all custom tags and then try to mount only the tag pertaining to the current view being switched. Here is my code. If I do unmount, then nothing is displayed on the page
index.html
<body>
<header label="Hire Zen" icon="img/user-8-32.png"></header>
<login-panel class="viewTag" id="loginView"></login-panel>
<candidates-panel id="candidatesView" class="viewTag"></candidates-panel>
<script src="js/bundle.js"></script>
</body>
app.js
function switchView(view) {
if(!view || view === '') {
view = 'login'
}
//unmount all other panels and mount only the panel that is required
//TODO: unmount all view panels and mounting only required panel is not working
//riot.unmount('.viewTag')
riot.mount(view+'-panel')
$('.viewTag').hide()
$(view+'-panel').show()
}
$(document).ready(function () {
RiotControl.addStore(new AuthStore())
RiotControl.addStore(new CandidatesStore())
riot.mount('header')
//register route change handler
riot.route(function (collection, id, action) {
switchView(collection)
})
riot.route.exec(function (collection, id, action) {
switchView(collection)
})
})
Answer for riot.js v2.1.0:
The function
riot.unmount(...)
is not available as far as I know. However, you can unmount saved tags.
mytag.unmount(true)
Source
The trick is to remember the mounted tags to be able to unmount them later:
var viewTag = riot.mount(document.getElementById('viewTag'))
viewTag.unmount(true)
You can store all those view tags in an object and loop them to unmount all and mount only the active one.
Source
Answer for 2.3.18
Based on the previous answer and this tutorial I have created following concept:
app.currentPage = null;
var goTo = function(page){
if (app.currentPage) {
app.currentPage.unmount(true); //unmount and keep parent tag
}
app.currentPage = riot.mount(page)[0]; //remember current page
};
riot.route(function() {
console.info("this page is not defined");
//do nothing (alternatively go to 404 page or home)
});
riot.route('/inventory', function(){
goTo('inventory');
});
riot.route('/options', function() {
goTo('options');
});
I think you are looking for riot.util.tags.unmountAll(tags)
How to achieve the goal?
index.html
var tags = [];
some.tag.html
var some = this;
tags.push(some);
unmountAllTags.js
riot.util.tags.unmountAll(tags);

Dynamically Adding / Removing Route in Durandal Router when application is loaded

I need help in dynamically adding/removing route in Durandal Router. What I want is after user is logged in then I would be able to add or remove specific route depending upon logged in user's type.
I tried to add/remove route from visibleRoutes/allRoutes array ... but get binding exception from knockout library...
I was hoping it would be common scenario... but still couldn't find any solution ... please help me in fixing this issue.
Thanks.
Wasim
POST COMMENTS:
I tried this function to dynamically hide/show route... and similary tried to add/remove route from allRoutes[] ... but then get exception on knockout bidning
showHideRoute: function (url,show) {
var routeFounded = false;
var theRoute = null;
$(allRoutes()).each(function (route) {
if (url === this.url) {
routeFounded = true;
var rt = this;
theRoute = rt;
return false;
}
});
if (routeFounded)
{
if (show)
{
visibleRoutes.push(theRoute);
}
else
{
visibleRoutes.remove(theRoute);
}
}
}
In Durandal 2.0.
You can enumerate the routes to find the one you wish to show/hide.
Then change the value of: nav property
Then run buildNavigationModel();
here is an example:
// see if we need to show/hide 'flickr' in the routes
for (var index in router.routes) {
var route = router.routes[index];
if (route.route == 'flickr') {
if (vm.UserDetail().ShowFlickr) { // got from ajax call
// show the route
route.nav = true; // or 1 or 2 or 3 or 4; to have it at a specific order
} else if (route.nav != false) {
route.nav = false;
}
router.buildNavigationModel();
break;
}
}
Durandal 2.0 no longer has the method visibleRoutes. I found that the following works for me.
router.reset();
router.map([
{ route: 'home', moduleId: 'home/index', title: 'Welcome', nav: true },
{ route: 'flickr', moduleId: 'flickr/index', title: '', nav: true }
])
.buildNavigationModel()
.mapUnknownRoutes('home/index', 'not-found');
This removes all previous routes, if you want to maintain current routes you could try using the router.routes property to rebuild the array of routes.
I had a similar requirement. If I were you, I would take another approach. Rather than adding/removing routes when application loads - get the right routes to begin with per user type.
Two options, (I use both)
1) have a json service provide the proper routes per user type, this approach would be good if you need to 'protect/obscure' routes... i.e. I don't want the route referenced on any client resource.
2) A simpler solution see Durandal.js: change navigation options per area
You can have a settings property identify the user type.
I hope this helps.
I had a similar problem: First, router.visibleRoutes() is an observable array. In other words, when you change its value, the routes automatically update. However, the items in this array are not observable, so to make a change you need to replace the entire array and not just make a change to a single item in it.
So, all you have to do is find which item in this array you want to remove, and then create a new array without this item, and set router.visibleRoutes() to this new array.
If, for example, you find out the it is the 3rd item, then one way of doing it is:
router.visibleRoutes(router.visibleRoutes().splice(2, 1))
Note that splice() returns a new array where an item is removed. This new array is put into router.visibleRoutes.