I've found it very difficult to find help online with this issue as no examples seem to match my use case. I'm basically wanting to check if I am on the right track in my approach.I have a single page Vue app:
Each row on the right is a component. On the left are listed three data sets that each possess values for the fields in the dashboard. I want it to be so that when you click on a dataset, each field updates for that set.
So if you click on 'Beds', the title becomes 'Beds' and all the fields populate the specific data for beds.
I want to do this without having separate pages for each dataset since that would seem to defeat the point of using a reactive framework like Vue. Only the embedded components should change, not the page.
I have installed Vue Router and have explored using slots and dynamic components but it is very hard to understand.
If someone experienced in Vue could just let me know the right broad approach to this I then know what I need to look into, at the moment it is difficult to know where to start. Thank you
You can use Vuex for that purpose.
Add property to the state, dataset for example. And mutation to change it. Every component on the right side should use that this.$store.state.dataset (or through mapState) for its own purposes. So when you're selecting one of listed datasets on the left side, it will mutate dataset in store with its own data.
Something like that:
store (there are alternate version, where we can use getter, but its little bit more complicated for just an example).
import Vue from 'vue';
const store = new Vuex.Store({
state: {
dataset: {}
},
mutations: {
setDataset(state, payload) {
Vue.set(state, 'dataset', payload);
}
}
});
one of the right side component
computed: {
dataset() {
return this.$store.state.dataset;
},
keywords() {
return this.dataset.keywords;
},
volume() {
return this.dataset.volume;
}
}
left menu
template:
{{dataset.title}}
code:
data() {
return {
datasets: [{
id: 1,
title: 'Sofas',
keywords: ['foo'],
volume: 124543
}]
}
},
methods: {
changeDataset(dataset) {
this.$store.commit('setDataset', dataset);
}
}
datasets is your data which you're loading from server.
BUT You can use some global variable for that, without Vuex. Maybe Vue observable, added in 2.6.
Related
I realise this is a common issue with people new to vue and vuex, but I've been using it for two years now and thought I understood the ins and outs. Yet I'm stumped. There must be something I'm overlooking.
We've got a couple of complex models that used to have layouts hard-coded in the front end, and now some of those come from the backend instead, so I added a store module to handle that:
import { ActionTree } from 'vuex';
import { RootState } from '#/store';
import request from '../../services/request';
import layouts from '../../layouts';
export const types = {
FETCH_LAYOUT: `${MODULE_NAME}${FETCH_LAYOUT}`,
};
const initialState = {
layout: layouts,
};
const actions: ActionTree<LayoutState, RootState> = {
async [FETCH_LAYOUT]({ commit, state }, id) {
if (!state[id]) {
const layout = await request.get(`layout/${id}`);
commit(types.FETCH_LAYOUT, { layout, id });
}
},
};
const mutations = {
[types.FETCH_LAYOUT](state: any, { layout, id }) {
state.layout[id] = layout;
},
};
export default {
namespaced: true,
state: initialState,
getters: {},
actions,
mutations,
};
Everything here seems to work fine: the request goes out, response comes back, state is updated. I've verified that that works. I've got two components using this, one of them the parent of the other (and there's a lot of instances of the child). They're far to big to copy them here, but the import part is simply this:
computed: {
...mapState({
layout: (state: any) => {
console.log('mapState: ', state.layout, state.layout.layout[state.modelName]);
return state.layout.layout[state.modelName];
},
}),
},
This console.log doesn't trigger. Or actually it looks like it does trigger in the parent, but not in the children. If I change anything in the front-end code and it automatically loads those changes, the child components do have the correct layout, which makes sense because it's already in the store when the components are rerendered. But doing a reload of the page, they lose it again, because the components render before the layout returns, and they somehow don't update.
I'm baffled why this doesn't work, especially since it does seem to work in the parent. Both use mapState in the same way. Both instantiate the component with Vue.component(name, definition). I suppose I could pass the layout down as a parameter, but I'd rather not because it's global data, and I want to understand how this can fail. I've considered if maybe the state.layout[id] = layout might not trigger an automatic update, but it looks like it should, and the parent component does receive the update. I originally had state[id] = layout, which also didn't work.
Using Vue 2.6.11 and Vuex 3.3.0
I'm trying to use Vue Chart.js to implement a chart selector to visualise various data.
Structure of application:
ChartPicker.vue (allow user to pick chart, create data, use dynamic component key to re-render component)
ChartWrapper.vue (receives props and passes them on, creates mixin for dynamic chart type)
ChartRender.vue (simply renders chart)
In the chart render component you usually you need to do 'extends: Bar', 'extends: Line' etc, therefore, requiring a ChartRender component type for each chart type. I found a neat solution that passes in the chart type to the chart mixins, then the final chart render makes no reference to chart type (not quite clear how this works even after looking at vue-chart.js code). This is the example I based my code on (it has no chart type selection):
https://codesandbox.io/s/vue-template-original-1czfi
So, I tried to extend functionality of that example to add a chart selector. It's working to an extent on chart type change: data changes, components re-render but the chart type doesn't change (even though it's being passed to the mixin dynamically)
I have a running example here:
https://codesandbox.io/s/vue-chart-issue-v2-twg3o
I've spent nearly a week trying to figure this out with no joy. I could create a workaround to use a separate ChartRender component for each chart type (e.g. ChartRenderBar, ChartRenderLine etc) but it moves away from DRY, so would rather not.
If anybody could help, I'd be VERY appreciative,
It is possible to dynamically update your chart type with vue-chartjs. The way I did it is by accessing the options in the chart itself and replacing it with the prop I get in which says which chart type it should become and then do an update on the chart. It is not the most elegant solution but it works.
<script>
import { Line, mixins } from 'vue-chartjs';
const { reactiveProp } = mixins;
export default {
extends: Line,
name: "LineChart",
mixins: [reactiveProp],
props: {
options: { type: Object },
chartType: { type: String }
},
mounted () {
this.renderChart(this.chartData, this.options);
},
watch: {
options: {
deep: true,
handler () {
this.$data._chart.options = this.options;
this.updateChart();
}
},
chartType (newVal) {
this.$data._chart.config.type = newVal;
this.updateChart()
}
},
methods: {
updateChart () {
this.$data._chart.update();
},
}
}
</script>
in Vuejs, it is not possible to change mixins after the component being created, and because of this I've used a wrapper component in my other solution, so I can pass a mixin dynamically before the component being created, but unfortunately, there is no way to have some kind of reactive mixin.
my solution for you current situation would be something like that:
https://codesandbox.io/s/vue-template-y5wsw
in the above solution, I have created two components, BarChart and LineChart
to switch between those dynamically, I am using one of the most awesome features in vuejs, Dynamic Component
and of course to avoid duplicating the data source, you can use vuex to share data between multiple components, or you can have the data in the parent page and access your dataset or options like
this.$parent['whatever data property in your parent component']
Hope you found this helpful.
I actually work on a project that consists of display data from Jsons on a Nuxt.js website using Vuetify. I have created a selector in my layout to choose which Json the user wants to display. I need to access this variable from all the different pages of my project.
Here is what my default.vue looks like :
<template>
<v-overflow-btn
:items="json_list"
label="Select an Json to display"
v-model="selected_json"
editable
mandatory
item-value="text"
></v-overflow-btn>
</template>
<script>
export default {
data() {
return {
selected_json: undefined,
json_list: [
{text: "first.json"},
{text: "second.json"},
],
}
}
}
</script>
The variable I would like to access from all my different pages is selected_json.
I see many things on the internet such as Vuex or a solution that consist to pass the variable with the URL. But I'm kind of newby in web programming (started Vue/Nuxt one week ago) and I don't really understand how to apply this in my project. So if there is a more easy way to do it or a good explaination, I'm interested!
Thanks in advance for your help :)
Using Vuex we can easily achieve what you want.
First of all create a file index.js in folder store (if you don't have a store folder then create it in the same directory where your pages, plugins, layouts etc folders are). Then paste this piece of code in index.js
//store/index.js
export const state = () => ({
selected_json: null
})
By doing this we set Vuex up. More precisely just state part of Vuex where if you don't know we store data accessible across your project.
Now we have to assign data from your default.vue to Vuex. We can achieve this by creating a mutation function through which we change state in Vuex. Add this to your index.js
//store/index.js
export const mutations = {
setSelectedJson(state, selectedJson) {
state.selected_json = selectedJson
}
}
Here function setSelectedJson takes two params, state which is automatically passed in by Nuxt.js and it includes all our Vuex state data. The second parameter selected_json we pass in ourselves.
Now in your default.vue we need to add a watcher for selected_json so we can update our Vuex when selected_json gets updated.
//layouts/default.vue
export default {
watch: {
selected_json(newValue) {
this.$store.commit("setSelectedJson", newValue)
}
}
}
We are almost done.
The last thing we need to do is to make a getter which is used to retrieve values from Vuex. A getter like this will do its job.
//store/index.js
export const getters = {
getSelectedJson(state) {
return state.selected_json
}
}
That's it.
Now you can access selected_json on any page you want by simply getting it from Vuex with this line of code.
this.$store.getters["getSelectedJson"]
I am trying to create a HN clone in 2 panes, but for some reason my vuex store is unable to update the component data.
This is the project link since there are too many files involved.
https://github.com/karansinghgit/hn-vue
This is what it looks like. My aim is to click on one of the articles on the left, and display the hn article with its comments on the right.
So far, I have understood that I need to use vuex to share data but the sharing is not taking place.
It just displays a function signature, when I want it to display the article ID.
The problem is in your store.js file. You are setting the default state for currentStory to Number. Setting it to an actual number instead should solve your problem:
export const store = new Vuex.Store({
state: {
currentStory: 0
},
mutations: {
setCurrentStory(state, ID) {
state.currentStory = ID
}
},
getters: {
currentStory: state => state.currentStory
}
})
Additionally, in story.vue, it is unnecessary to specify storyID in the data as you already have it as a computed property (there might be an error thrown for duplicate keys)
I'm new to Vue.js. I followed the tutorial here - https://coligo.io/dynamic-components-in-vuejs/ - on dynamic components, to give me a dynamic layout I liked, for listing products and allowing the user to switch to an edit view when they click on one of the products in the table. So, I have a 'list-products' component and an 'edit-product' component, and which one is displayed is dependent on the state of 'currentView' in the main Vue instance.
<div id="content">
<keep-alive>
<component :is="currentView"></component>
</keep-alive>
</div>
The switching is all working fine when currentView is changed. What I haven't got figured out is how best to pass the product information to the edit component such that it ends up as data. I suppose the list and edit components are two sibling components of the main Vue instance, instantiated at the same time. What I need to do is when I click on a row in listing table, have the product object used for building that row made available to the edit component. I'm not sure how I do that (at least, in a proper Vue way). When the displayed component is switched (via the change in 'currentView'), is some event called for the newly (re)displayed component? If so, I could presumably call some function?
LATER: I have determined that the 'activated' hook is called when I switch to the edit-product component, which I imagine I should be able to use somehow. Now to figure that out.
You could use Vuex for that. Vuex is a Flux inspired state management library for Vue.
Your application basically has two different states: (1) no product selected (list-products component), and (2) any product selected (edit-product). When this is modeled with Vuex, the idea is to keep the currently selected product in a so-called store and let the components figure out their internal state depending on the store state. Here's an example:
Create a store to keep the application state:
const store = new Vuex.Store({
state: {
selectedProduct: null
},
getters: {
selectedProduct: state => state.selectedProduct
},
mutations: {
selectProduct: (state, data) => state.selectedProduct = data
}
});
Handle product selection in your list-products component:
methods: {
selectProduct(product) {
this.$store.commit('selectProduct', product);
}
}
Display the current product in edit-product:
Vue.component('edit-product', {
store,
template: '<div>{{selectedProduct.name}}</div>',
computed: Vuex.mapGetters(['selectedProduct'])
});
And finally switch the components depending on the state:
new Vue({
el: '#app',
store,
computed: Object.assign(Vuex.mapGetters(['selectedProduct']), {
currentView() {
return this.selectedProduct ? 'edit-product' : 'list-products'
}
})
});
Here's a basic working JSFiddle.