I have a project where i need to use a store to manage a root component with many child components,
now i need to make copies of that root component with different props values, but the state is shared across the entire app, is there a way to scope the store it to root component?
example to illustrate the problem:
App.vue
<script>
import ComponentA from './components/ComponentA.vue'
</script>
<template>
<ComponentA name="comp1"/>
<ComponentA name="comp2"/>
<ComponentA name="comp3"/>
</template>
ComponentA.vue
<script>
import { store } from './store.js'
export default{
props: ["name"],
data(){
return { store }
}
}
</script>
<template>
{{name}}:{{store.count}}
<button #click="store.increment()">increment</button>
</template>
store.js
import { reactive } from 'vue'
export const store = reactive({
count: 0,
increment(){
this.count++
}
})
I don't think that's possible without some sort of refactor.
The global store is helpful if you don't want to deal with prop drilling (and event emitting), but in order to scope it, the component ant its children will need to know which store to use. I think the easiest way to implement that would be to make use of provide/inject. You can use provide/inject to share a store instance
import { reactive } from 'vue'
export function createStoreInstance() {
return reactive({
count: 0,
increment(){
this.count++
}
})
}
then, in your component you would generate the instance during creation
<script>
import { createStoreInstance } from './store.js'
export default {
components: {
GrandChild
},
provide() {
return {
store: this.store
}
},
beforeCreate(){
this.store = createStoreInstance()
},
methods:{
increment(){
this.store.count ++
}
}
}
</script>
and in the child component just get the store
<script>
export default {
inject: [ 'store']
}
</script>
<template>
<p>
{{store}}
</p>
</template>
here is a SFC playground link
You can also use a global store that would accommodate keyed instances, and then use provide inject to pass the key to the children, but I think that would make the store more complicated, but there might be use cases where that may be a better approach (like if you want to be able to save the store state)
Related
I want to separate my logic from the component in vue.
What I have in mind is this:
One file for HTML template, the data pass as props.
Another file that has a lot of functions and getters that gets the data from the store/API.
So after I search a lot I understand I need something like "hooks in reacts".
What I find is u3u/vue-hooks.
My question is what are the benefits to use this idea/library? cause it seems like I do the same with and without vue-hooks.
for example:
foo.ts:
import { computed, defineComponent } from '#vue/composition-api';
export default defineComponent({
name: 'foo',
props: {
icon: {
type: String,
default: '',
},
},
setup(props) {
const iconName = computed(() => props.icon);
return {
iconName,
};
},
});
and foo.vue:
<template>
<div>{{iconName}}</div>
</template>
<script lang="ts" src="./foo.ts">
</script>
<style lang="scss">
</style>
So until here, I separate the logic from the component and I can choose which file to attach the view.
But I can do it with the class as well.
just to change the foo.ts file to:
import { Component, Prop, Vue } from 'vue-property-decorator';
#Component
export default class Foo extends Vue {}
I would like it if anyone explains to me - if hooks are the way to separate the logic from the UI? and should I use vue-hooks to do it?
I have a Vuex state where i define a selected pdf:
selectedPDF: "/svg/example.pdf"
(hardcoded for testing purposes)
Vuex getter:
getSelectedPDF: state => { return state.selectedPDF; }
And here's basic component structure:
<template>
<div>
<pdf :src="selectedPDF"></pdf>
</div>
</template>
<script>
import pdf from "vue-pdf";
import { mapGetters } from "vuex";
export default {
name: "ExamplePdf",
data: () => {
return {};
},
computed: {
...mapGetters({
selectedPDF: "selectedPDF"
})
},
components: {
pdf
}
};
My idea is load pdfs in the Vuex state dynamically, and then use the example component above to display said pdf in multiple places. However, once i use the component somewhere (where it displays the pdf properly), if i try to use it somewhere else, it just displays blank page.
Is it actually possible to do this with this npm module?
I'm new to Vue, so it's likely I misunderstand something. I want to call a vuex action inside a local function in App.vue like so:
<template>
<div id="app">
<button #click="runFunction(1)">Test</button>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default{
data() { return { } },
methods: {
...mapActions(['doAction']),
buttonClicked: (input) => { runFunction(input) }
}
}
function runFunction(input){
doAction({ ID: input });
}
</script>
The action calls a mutation in store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
IDs: []
},
mutations: {
doAction: (state, id) => { state.IDs.push(id) }
},
actions: {
doAction: ({ commit }, id) => { commit('doAction', id) }
}
})
I also have a main.js that sets up the vue:
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
The error I'm getting is:
ReferenceError: doAction is not defined
at runFunction
How can I call the mapped action inside a function? Version is Vue 2.6.10
There are several problems with defining runFunction as a 'local function':
function runFunction(input){
doAction({ ID: input });
}
Firstly, this is just a normal JavaScript function and the usual scoping rules apply. doAction would need to be defined somewhere that this function can see it. There is no magic link between this function and the component defined in App.vue. The function will be accessible to code in the component, such as in buttonClicked, but not the other way around.
The next problem is that it won't be available within your template. When you write runTemplate(1) in your template that's going to be looking for this.runTemplate(1), trying to resolve it on the current instance. Your function isn't on the current instance. Given your template includes #click="runFunction(1)" I'm a little surprised you aren't seeing a console error warning that the click handler is undefined.
mapActions accesses the store by using the reference held in this.$store. That reference is created when you add the store to your new Vue({store}). The store may appear to be available by magic but it's really just this.$store, where this is the current component.
It isn't really clear why you're trying to write this function outside of the component. The simplest solution is to add it to the methods. It'll then be available to the template and you can access doAction as this.doAction.
To keep it as a separate function you'd need to give it some sort of access to the store. Without knowing why you want it to be separate in the first place it's unclear how best to achieve that.
Of course it is not defined outside your instance .... you have to import the exported store from store.js on your function component :
<script>
import { mapActions } from 'vuex'
import store from 'store.js'
export default{
data() { return { } },
methods: {
...mapActions(['doAction']),
buttonClicked: (input) => { runFunction(input) }
}
}
function runFunction(input){
store.commit({ ID: input });
}
</script>
I got an array of data in one component which I want to access in another component but cannot get it right
My idea was to just import component one in component two and thought I could access the data in that way but it didnt work.
here is what I got so far ...
Component 1:
export default {
data() {
return {
info: [
{
id: 1,
title: "Title One"
},
{
id: 2,
title: "Title Two"
},
Component 2:
<template>
<div>
<div v-for="item in info" v-bind:key="item.id">
<div>{{ item.title }} </div>
</div>
</div>
</template>
<script>
import ComponentOne from "../views/ComponentOne ";
export default {
components: {
ComponentOne
}, But after this I am a bit lost
Can anyone point my to the right direction it would be very much appreciated!
In order to access shared data, the most common way is to use Vuex. I'll get you going with the super basics with a module system as it does take a little reading.
npm install vuex --save
Create new folder called store in the src directory.
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import example from './modules/example'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
example // replace with whatever you want to call it
}
})
src/main.js
// add to your imports
import store from './store/index'
...
// Change your Vue instance init
new Vue({
router,
store, // <--- this bit is the thing to add
render: h => h(App)
}).$mount('#app')
/src/store/modules/example.js
// initial state
const state = {
info: []
}
// getters
const getters = {}
// actions
const actions = {
}
// mutations
const mutations = {
set (state, newState) {
state.info.splice(0)
state.info.push.apply(state.info, newState)
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
To update the store when you get info, from any component you can use this.$store.commit('example/set', infoArray) where the first parameter follows the pattern of module name/mutation function name, and the second parameter is the 'new state' that you want updated.
To access the data from the store, you can access it from your components as a computed property:
computed: {
info () {
return this.$store.state.example.info
}
}
Obviously you can use getters and actions and other stuff, but this will get you going and you can read up and modify the Vuex store once you get comfortable and understand how it works.
Let's say if you do not want to use any other state management like vuex then you can share with the use of mixins.
Well, you can achieve it with the use of Vue.mixins.
Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixins will be “mixed” into the component’s own options.
Mixins official docs
Hope this helps!
Trying to learn vuejs I got to the question how to pass any data from one component to all, using $emit but without using any #click.
It is possible some how that the data to be just available and grab it any time, without using the click?
Let's say we have this example with normal #click and $emit.
main.js
export const eventBus = new Vue()
Hello.vue
<template>
<div>
<h2>This is Hello component</h2>
<button
#click="emitGlobalClickEvent()">Click me</button>
</div>
</template>
<script>
import { eventBus } from '../main'
export default {
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
methods: {
emitGlobalClickEvent () {
eventBus.$emit('messageSelected', this.msg)
}
}
}
</script>
User.vue
<template>
<div>
<h2>This is User component</h2>
<user-one></user-one>
</div>
</template>
<script>
import { eventBus } from '../main'
import UserOne from './UserOne.vue'
export default {
created () {
eventBus.$on('messageSelected', msg => {
console.log(msg)
})
},
components: {
UserOne
}
}
</script>
UserOne.vue
<template>
<div>
<h3>We are in UserOne component</h3>
</div>
</template>
<script>
import { eventBus } from '../main'
export default {
created () {
eventBus.$on('messageSelected', msg => {
console.log('From UserOne message !!!')
})
}
}
</script>
I want to get this message : Welcome to Your Vue.js App from Hello.vue in all components, but without #click, if is possible.
You can create another Javascript file which holds an Object with your initial state. Similar to how you define data in your components.
In this file your export your Object and import it in all Components which need access to this shared state. Something along the lines of this:
import Store from 'store';
data() {
return {
store
}
}
This might help:
https://v2.vuejs.org/v2/guide/state-management.html
At this point if you app grows even more in complexity you might also start checking out Vuex which helps to keep track of changes(mutations) inside of your store.
The given example is essential a very oversimplified version of Vuex.