Vue.js - Open/close a dynamic Sidebar thought diferrent components (Navbar to Sidebar) using vuex - boolean

I'm trying to make a dynamic Sidebar on my website, but the menu button is in another component (Navbar). How can I get them to communicate with each other through vuex? Look, I know how to do it in the same component, but I'm struggling here to pass this boolean state from Navbar to Sidebar.

Define your store as follows:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
sideBarOpen: false
},
getters: {
g_sideBarOpen(state){
return state.sideBarOpen
}
},
mutations: {
toggleSideBar(state){
state.sideBarOpen = !state.sideBarOpen;
}
},
});
In NavBar component click listener for menu button
<template>
<button #click="toggleSideBar" class=myMenuBtn"></button>
</template>
<script>
export default{
methods:{
toggleSideBar(){
this.$store.commit('toggleSideBar');
}
}
}
</script>
now in the main component where you host the SideBar component
<template>
<side-bar v-show="showSideBar"></side-bar>
</template>
<script>
import SideBar from './SideBar'
export default{
components:{
'side-bar': SideBar
},
computed:{
showSideBar(){
this.$store.getters.g_sideBarOpen;
}
}
}
</script>

The whole purpose of using Vuex is to have a common state across your components. You don't have to communicate this from one component, they share the state.
If you commit a mutation in one component, to set a variable : state.myVar, you can access the modified this.$store.state.myVar in the other component, which will always reflect the modified value.
Please add your code samples if it is not working like this.

Related

Is it possible in vue3 to access the root DOM element in a child component slot? I am trying to use a 3rd party library (sortablejs) in vue3

In vue2 I could use this.$el
export default {
render() {
return this.$slots.default[0]
},
mounted() {
Sortable.create(this.$el, {});
})
}
If, in vue3 I try to use this.$slots.default()[0] I can't see how to target the element.
If I use a template ref, I can get the div, but not the contained slot.
The closest question / answer I have found is here Vue 3 Composition API - How to get the component element ($el) on which component is mounted
but this also seems to give the div, but not the slot $el.
This was extremely powerful in vue2 because sortable could be passed a ul, or a div, or another constructed sortable vue component in a slot, and work without the element having to be defined in the child component and I can't work out how to replicate this in vue3.
I originally came across this in a screen cast by Adam Wathan: "Building a Sortable Component with Vue.js", but this was vue2.
I've come up with the following (perhaps there are better out there)
Use template ref:
<template>
<div ref="root">
<slot></slot>
</div>
</template>
Then in the script:
import { ref, onMounted } from 'vue'
export default {
setup() {
const root = ref(null)
onMounted(() => {
// the DOM element will be assigned to the ref after initial render
// console.log(root.value.children[0]) // this is your $el
let el = root.value.children[0]
Sortable.create(el, {})
})
return {
root
}
}
}

FOUC when using #material-ui/core with NextJS/React

My simple NextJS page looks like this (results can be viewed at https://www.schandillia.com/):
/* eslint-disable no-unused-vars */
import React, { PureComponent, Fragment } from 'react';
import Head from 'next/head';
import compose from 'recompose/compose';
import Layout from '../components/Layout';
import { withStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
const styles = {
root: {
textAlign: 'center',
paddingTop: 200,
},
p: {
textTransform: 'uppercase',
color: 'red',
},
};
class Index extends PureComponent {
render() {
const { classes } = this.props;
const title = 'Project Proost';
const description = 'This is the description for the homepage';
return (
<Fragment>
<Head>
<title>{ title }</title>
<meta name="description" content={description} key="description" />
</Head>
<Layout>
<p className={classes.p}>amit</p>
<Button variant="contained" color="secondary">
Secondary
</Button>
</Layout>
</Fragment>
);
}
}
export default withStyles(styles)(Index);
I am importing a bunch of components off the #material-ui/core library to style my items. I also have a local style definition assigned to a style constant.
What seems to be happening here is that my style isn't getting rendered on the server which is why the files being served upon load are sans-style. And then the CSS gets rendered by the client-side code. As a result, there's a flash of unstyled content that lasts almost a second, long enough to be noticable.
Any way to fix this? The entire codebase is up for reference at https://github.com/amitschandillia/proost/tree/master/web.
I ran a similar problem when tried to make a production build of my app, that uses material-ui. I manage to solve by adding a JSS Provider like this:
import JssProvider from "react-jss/lib/JssProvider";
class App extends Component {
render() {
<JssProvider>
*the rest of your material-ui components*
</JssProvider>
}
}
Here's the solution - https://github.com/mui-org/material-ui/blob/master/examples/nextjs/pages/_document.js .
Basically, all you need to do is to sync server-side class names with client-side. The link above shows what you need to do to fix that issue.

What is the best way to post form with multiple components using Vue js

as I'm on my Vue spree (started recently but so far I'm really enjoying learning this framework) couple of questions rised up. One of which is how to post form from multiple components. So before I continue forward I wanted to ask you what are you thinking about this way of structuring and point me in right direction if I'm wrong.
Here it goes.
I'm working on a SPA project using ASP.NET CORE 2.1 and Vue JS Template (with webpack)(https://github.com/MarkPieszak/aspnetcore-Vue-starter) and my project is structured in several containers, something like this:
In my app-root i registered several containers
<template>
<div id="app" class="container">
<app-first-container></app-first-container>
<app-second-container></app-second-container>
<!--<app-third-container></app-third-container>-->
<app-calculate-container></app-calculate-container>
<app-result-container></app-result-container>
</div>
</template>
<script>
// imported templates
import firstContainer from './first-container'
import secondContainer from './second-container'
import calculateContainer from './calculateButton-container'
//import thirdContainer from './third-container'
import resultContainer from './result-container'
export default {
components: {
'app-first-container': firstContainer,
'app-second-container': secondContainer,
// 'app-third-container': thirdContainer,
'app-calculate-container': calculateContainer,
'app-result-container': resultContainer
}
}
</script>
In my first container I'm having several dropdowns and two input fields with my script file where I'm fetching data from API and filling dropdowns and input fields with fetched data.
Something like this ( entered some dummy code for demonstration)
<template>
<div>
<h1>Crops table</h1>
<p>This component demonstrates fetching data from the server. {{dataMessage}}</p>
<div class="form-row">
<div class="form-group col-md-6">
<label for="exampleFormControlSelect1" class="col-form-label-sm font-weight-bold">1. Some text</label>
<select class="form-control" id="exampleFormControlSelect1" v-model="pickedCropType" #change="getCropsByType()">
<option v-for="(cropType, index) in cropTypes" :key="index" :value="cropType.id" :data-imagesrc="cropType.imgPath">{{ cropType.name }}</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="exampleFormControlSelect2" class="col-form-label-sm font-weight-bold">2. Some text</label>
<select class="form-control" id="exampleFormControlSelect2">
<option v-for="(crop, index) in cropSelectList" :key="index" :value="crop.id">{{ crop.name }}</option>
</select>
</div>
</div>
</div>
</template>
<script>
import { mapActions, mapState } from 'vuex'
export default {
data() {
return {
cropTypes: null,
cropSelectList: null,
crops: null,
pickedCropType: null,
}
},
methods: {
loadPage: async function () {
try {
//Get crop types and create a new array with crop types with an added imgPath property
var cropTypesFinal = [];
let responseCropTypes = await this.$http.get(`http://localhost:8006/api/someData`);
responseCropTypes.data.data.forEach(function (element) {
cropTypesFinal.push(tmpType);
});
} catch (err) {
window.alert(err)
console.log(err)
}
},
getCropsByType: async function () {
//Get crops by crop type
let responseCrops = await this.$http.get(`http://localhost:8006/api/crop/Type/${this.pickedCropType}`);
var responseCropsData = responseCrops.data.data;
this.cropSelectList = responseCropsData;
}
},
async created() {
this.loadPage()
}
}
</script>
And in my second container I have different dropdowns and different input fields with different scripts etc.
So, my questions are:
1.) I'm having required data form field in first container and in second container I'm having additional data and my submit button is separated in third container (app-result-container). So, is this proper and logical way of structuring containers if not can you point me in right direction?
2.) Is it smart to input script tag in every container where I'm processing/fetching/submitting some data for that particular container? Should I put scripts tag in separated file and keep structure clean, separating html from js file.
Example:
import { something } from 'something'
export default {
data () {
return {
someData: 'Hello'
}
},
methods: {
consoleLogData: function (event) {
Console.log(this.someData)
}
}
}
3.) Can I send input values from one container to another (In my particular case from first and second container to app-calculate-container(third container))?
How to on submit return results container with calculated imported values
If you want components to communicate or share data with one another, you will need to either emit an event from one component up to the parent and pass it down via props, or use some kind of state management model, like Vuex, where each of your components can listen to the store.
Take a look at this code sandbox: https://codesandbox.io/s/8144oy7xy2
App.vue
<template>
<div id="app">
<child-input #input="updateName" />
<child-output :value="name" />
</div>
</template>
<script>
import ChildInput from "#/components/ChildInput.vue";
import ChildOutput from "#/components/ChildOutput.vue";
export default {
name: "App",
components: {
ChildInput,
ChildOutput
},
data() {
return {
name: ""
};
},
methods: {
updateName(e) {
this.name = e.target.value;
}
}
};
</script>
ChildInput.vue
<template>
<input type="text" #input="changeHandler">
</template>
<script>
export default {
name: "ChildInput",
methods: {
changeHandler(e) {
this.$emit("input", e);
}
}
};
</script>
ChildOutput.vue
<template>
<p>{{ value }}</p>
</template>
<script>
export default {
name: "ChildOutput",
props: {
value: {
type: String,
default: ""
}
}
};
</script>
What's going on?
The ChildInput component is a text field and on every change inside it, fires an event (emits using this.$emit() and passes the whole event up).
When this fires, App is listening to the change, which fires a method that updates the name data property.
Because name is a reactive data property and is being passed down as a prop to the ChildOutput component, the screen re-renders and is updated with the text written.
Neither ChildInput nor ChildOutput knows about one another. It's the parent that listens to the event passed to it, then passes the new prop down.
This way of working is fine and simple to understand, but I would strongly recommend looking at Vuex, as this method can get messy and complicated when you go beyond trivial tasks.

What is sane way in vuejs + vuex form handling?

I have a large forms to submit in single page.
<container>
<formA>
<formB>
<formC>
<submitButton>
<container>
it looks apparently like this. and I have a store which save every form data. then when user click submit button, I gather all form data using vuex store.
The problem is I need to update the form data in store everytime.
so I'll be like this in vue component
watch: {
userInput (val) {
this.updateState(val)
}
update state when input changes by watching form data(binded with v-model).
or like this which is documented in vuex doc.
userInput: {
get () {
return this.$store.state.userInput
},
set (val) {
this.updateState(val)
}
}
well.. I don't think these are good idea. Is there any better way to form handling with vuex?
I made a little tool which makes form handling wit Vuex a lot easier: vuex-map-fields
Example
Store
import Vue from 'vue';
import Vuex from 'vuex';
// Import the `getField` getter and the `updateField`
// mutation function from the `vuex-map-fields` module.
import { getField, updateField } from 'vuex-map-fields';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
fieldA: '',
fieldB: '',
},
getters: {
// Add the `getField` getter to the
// `getters` of your Vuex store instance.
getField,
},
mutations: {
// Add the `updateField` mutation to the
// `mutations` of your Vuex store instance.
updateField,
},
});
Component
<template>
<div id="app">
<input v-model="fieldA">
<input v-model="fieldB">
</div>
</template>
<script>
import { mapFields } from 'vuex-map-fields';
export default {
computed: {
// The `mapFields` function takes an array of
// field names and generates corresponding
// computed properties with getter and setter
// functions for accessing the Vuex store.
...mapFields([
'fieldA',
'fieldB',
]),
},
};
</script>
You can read more about vuex-map-fields on my blog: How to Handle Multi-row Forms with Vue, Vuex and vuex-map-fields
I would use deep watchers for this and have all fields in a object, you could use multiple approaches for saving the data, iterating over Object.keys to store each field with it's variable name in the form object, or storing the entire form, whatever you might need.
You could also use v-model.lazy="form.myfield" to indicate that you only want the binding to update once the user has left the field.
Form component
<template>
<div>
<!-- You can optionally use v-model.lazy="form.field1" to only update once user has exited the field or pressed enter -->
<input v-model="form.field1" />
<input v-model.lazy="form.field2" />
</div>
</template>
<script>
export default {
props: ['value'],
data: function () {
return {
internalForm: {
field1: null,
field2: null
}
}
},
watch: {
internalForm: {
handler: function (newValue) {
// Emit new form object to parent component so we can use v-model there
this.$emit('input', this.form)
// Or save form data
this.handleFormSave(this.form)
},
// Tell vue to do a deep watch of entire form object to watch child items in the object
deep: true
}
}
}
</script>
Parent component
<template>
<form-component v-model="forms.form1" />
<submit-button #click="saveAllFormData" />
</template>
<script>
export default {
data: function () {
return {
forms: {
form1: null // This will be updated when 'input' is emitted
}
}
},
watch: {
forms: {
handler: function (newValue) {
if (allFormsValid && readyToSave)
saveAllFormData(newValue);
},
deep: true
}
}
}
</script>
I had headache regarding this probem to.
Vuex doc describes that we need to update store for every field.
It's a loot of typing whatfor?
We make one solution that works.
It based on cloning store object to local one.
//We are passing (vuexstore) 'item' object from parent component:
//<common-item v-bind:item="item" ....
props: ['item'],
// create localItem - this is reactive object for vuex form
data: () => {
return {
localItem: null
}
},
// make clone on created event
created: function() {
this.localItem = this._clone(this.item)
},
// watch vuexstore 'item' for changes
watch: {
item: function(val) {
this.localItem = this._clone(this.item)
}
},
// map mutations and update store on event
methods: {
...mapMutations([
'editItem'
]),
updateItemHandler: function() {
this.editItem({ item: this._clone(this.localItem) })
},
_clone: function(o){
return JSON.parse(JSON.stringify(o))
}
},
Inside form use:
<input v-model="localItem.text" #keyup="updateItemHandler" type="text" class="form-control"></input>
I think this is only lack of vuex. There should be much shorter and built in solution.

Reactjs together with TinyMCE editor code plugin

I'm using Reactjs together with the tinyMCE 4.1.10 html editor (together with the code plugin) and bootsrap css + js elements. A fairly working setup after a few quirks with the editor have been removed (manual destruction if the parent element unmounts)
Now the question: The textarea input of the code plugin does not receive any focus, click or key events and is basically dissabled. Setting the value via javascript works just fine, but it does not function as a normal html input.
It is opened as the following:
datatable as react components
opens bootsrap modal as react component
initializes tinymce on textareas inside of the modal
loads the code plugin (which itself then is not accepting any kind of input anymore)
My initilization of the editor looks like this:
componentDidMount: function(){
tinymce.init({
selector: '.widget-tinymce'
, height : 200
, resize : true
, plugins : 'code'
})
}
My guess would be, that react.js is somehow blocking or intersepting the events here. If I remove the react modal DOM, it is just working fine.
Does anybody has an idea, what is causing this or how to simply debug it further?
Thx a lot!
if you are using Material UI. disable Material UI Dialog's enforce focus by adding a prop disableEnforceFocus={true} and optionally disableAutoFocus={ true}
What does your html/jsx look like in your component?
My guess is that react might be treating your input as a Controlled Component
If you're setting the value attribute when you render, you'll want to wait, and do that via props or state instead.
Alright, so it turned out that bootstrap modals javascript is somehow highjacking this. In favor of saving some time I decided not to dig realy into this but just to create my own modal js inside of the jsx.
Aparently there is also React Bootstrap, but it looks at the moment to much beta for me in order to take this additional dependency in.
The final code looks like this, in case it becomes handy at some point:
Modal = React.createClass({
show: function() {
appBody.addClass('modal-open');
$(this.getDOMNode()).css('opacity', 0).show().scrollTop(0).animate({opacity: 1}, 500);
}
, hide: function(e){
if (e) e.stopPropagation();
if (!e || $(e.target).data('close') == true) {
appBody.removeClass('modal-open');
$(this.getDOMNode()).animate({opacity: 0}, 300, function(){
$(this).hide();
});
}
}
, showLoading: function(){
this.refs.loader.show();
}
, hideLoading: function(){
this.refs.loader.hide();
}
, render: function() {
return (
<div className="modal overlay" tabIndex="-1" role="dialog" data-close="true" onClick={this.hide}>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" onClick={this.hide} data-close="true" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 className="modal-title" id="myModalLabel">{this.props.title}</h4>
</div>
<div className="modal-body" id="overlay-body">
{this.props.children}
<AjaxLoader ref="loader"/>
</div>
</div>
</div>
</div>
);
}
})
Best wishes
Andreas
Material UI: disable Dialog's enforce focus by adding a prop disableEnforceFocus={true} and optionally disableAutoFocus={ true}