Pass range input value on change in Vue 2 - javascript

In Vue 2: I have an App component, which has a Slider component:
App.vue
<template>
<div>
<Slider :foo="store.foo"></Slider>
</div>
</template>
<script>
import store from './components/store.js';
import Slider from './components/Slider.vue';
export default {
name: 'app',
components: { Slider },
data() {
return {
store: store
}
},
methods: {
changeFoo(foo) {
console.log('change!', foo);
},
},
}
</script>
Slider.vue
<template>
<div>
<input type="range" min="1" max="100" step="1" #change="changeFoo" />
</div>
</template>
<script>
export default {
props: ['foo'],
methods: {
changeFoo() {
this.$emit('changeFoo', foo);
}
}
}
</script>
The problem is that the value of the slider is not being passed in the emit statement in Slider.vue. I can see why - but I'm not sure how to fix it. I tried doing:
v-model="foo"
in the input element, but Vue gives a warning that I'm not allowed to mutate props.

Instead of using prop create a new data variable for slider and pass this variable in the emit, like this:
<template>
<div>
<input v-model="sliderVal" type="range" min="1" max="100" step="1" #change="changeFoo" />
</div>
</template>
<script>
export default {
props: ['foo'],
data: function() {
return {
sliderVal: ""
}
}
methods: {
changeFoo() {
this.$emit('changeFoo', this.sliderVal);
}
}
}
</script>
Also in App.vue you will have to listed to this emitted event like this:
<template>
<div>
<Slider :foo="store.foo" #change-foo="changeFoo"></Slider>
</div>
</template>

Related

How to hide content when clicked checkbox from different components in vuejs?

//inputtwo.vue
<template>
<div><input type="checkbox" v-model="checked" />one</div>
</template>
<script>
export default {
name: "inputtwo",
components: {},
data() {
return {};
},
};
</script>
//maincontent.vue
<template>
<div>
<div class="container" id="app-container" v-if="!checked">
<p>Text is visible</p>
</div>
<common />
</div>
</template>
<script>
export default {
name: "maincontent",
components: {},
data() {
return {
checked: false,
};
},
methods: {
hidecont() {
this.checked = !this.checked;
},
},
};
</script>
//inputone.vue
<template>
<div><input type="checkbox" v-model="checked" />one</div>
</template>
<script>
export default {
name: "inputone",
components: {},
data() {
return {};
},
};
</script>
How to hide content of checkbox from different components in Vuejs
I have three components called inputone(contains checkbox with v-model),inputtwo (contains checkbox with v-model),maincontent.(having some content and logic), So when user click on checkboxes from either one checckbox(one,two). i schould hide the content.
Codesanfdbox link https://codesandbox.io/s/crimson-fog-wx9uo?file=/src/components/maincontent/maincontent.vue
reference code:- https://codepen.io/dhanunjayt/pen/mdBeVMK
You are actually not syncing the data between components. The main content checked never changes. You have to communicate data between parent and child components or this won't work. And try using reusable components like instead of creating inputone and inputtwo for same checkbox create a generic checkbox component and pass props to it. It is a good practice and keeps the codebase more manageable in the longer run.
App.vue
<template>
<div id="app">
<maincontent :showContent="showContent" />
<inputcheckbox text="one" v-model="checkedOne" />
<inputcheckbox text="two" v-model="checkedTwo" />
</div>
</template>
<script>
import maincontent from "./components/maincontent/maincontent.vue";
import inputcheckbox from "./components/a/inputcheckbox.vue";
export default {
name: "App",
components: {
maincontent,
inputcheckbox,
},
computed: {
showContent() {
return !(this.checkedOne || this.checkedTwo);
},
},
data() {
return {
checkedOne: false,
checkedTwo: false,
};
},
};
</script>
checkbox component:
<template>
<div>
<input
type="checkbox"
:checked="value"
#change="$emit('input', $event.target.checked)"
/>
{{ text }}
</div>
</template>
<script>
export default {
name: "inputcheckbox",
props: ["value", "text"],
};
</script>
Content:
<template>
<div class="container" id="app-container" v-if="showContent">
<p>Text is visible</p>
</div>
</template>
<script>
export default {
name: "maincontent",
props: ["showContent"]
}
</script>
https://codesandbox.io/embed/confident-buck-kith5?fontsize=14&hidenavigation=1&theme=dark
Hope this helps and you can learn about passing data between parent and child components in Vue documentation: https://v2.vuejs.org/v2/guide/components.html
Consider using Vuex to store and maintain the state of the checkbox. If you're not familiar with Vuex, it's a reactive datastore. The information in the datastore is accessible across your entire application.

VueJS warning when using dynamic components and custom-events

So, I get this warning:
" Extraneous non-emits event listeners (addNewResource) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option."
And I don't understand why. I am using dynamic components with 2 custom events. I've tried adding both of the emitted events to the emits object of both components.
App.vue
<template>
<AppHeader />
<NavigationBar #select-component="selectComponent" />
<keep-alive>
<component
:is="selectedComponent"
v-bind="componentProps"
#delete-resource="deleteResource"
#add-new-resource="addNewResource"
></component>
</keep-alive>
</template>
<script>
import AppHeader from "./components/SingleFile/AppHeader.vue";
import NavigationBar from "./components/NavigationBar.vue";
import LearningResources from "./components/LearningResources.vue";
import AddResource from "./components/AddResource.vue";
export default {
components: {
AppHeader,
NavigationBar,
LearningResources,
AddResource,
},
data() {
return {
selectedComponent: "learning-resources",
learningResources: [
{
name: "Official Guide",
description: "The official Vue.js documentation",
link: "https://v3.vuejs.org",
},
{
name: "Google",
description: "Learn to google...",
link: "https://www.google.com/",
},
],
};
},
methods: {
selectComponent(component) {
this.selectedComponent = component;
},
deleteResource(name) {
this.learningResources = this.learningResources.filter(
(resource) => resource.name !== name
);
},
addNewResource(newResourceObject) {
const newResource = {
name: newResourceObject.title,
description: newResourceObject.description,
link: newResourceObject.link,
};
this.learningResources.push(newResource);
},
},
computed: {
componentProps() {
if (this.selectedComponent === "learning-resources") {
return {
learningResources: this.learningResources,
};
}
return null;
},
},
};
</script>
AddResource.vue
<template>
<base-card>
<template #default>
<form #submit.prevent>
<div>
<label for="title">Title</label>
<input type="text" v-model="newResource.title" />
</div>
<br />
<div>
<label for="description">Description</label>
<textarea rows="3" v-model="newResource.description" />
</div>
<br />
<div>
<label for="link">Link</label>
<input type="text" v-model="newResource.link" />
</div>
<button #click="$emit('add-new-resource', newResource)">
Add Resource
</button>
</form>
</template>
</base-card>
</template>
<script>
import BaseCard from "./Base/BaseCard.vue";
export default {
components: {
BaseCard,
},
emits: ["add-new-resource"],
data() {
return {
newResource: {
title: "",
description: "",
link: "",
},
};
},
};
</script>
LearningResources.vue
<template>
<base-card v-for="resource in learningResources" :key="resource.name">
<template #header>
<h3>{{ resource.name }}</h3>
<button #click="$emit('delete-resource', resource.name)">Delete</button>
</template>
<template #default>
<p>{{ resource.description }}</p>
<p><a :href="resource.link">View Resource</a></p>
</template>
</base-card>
</template>
<script>
import BaseCard from "./Base/BaseCard.vue";
export default {
components: {
BaseCard,
},
props: {
learningResources: Array,
},
emits: ["deleteResource"],
};
</script>
Seems to be because <component> is being used for two separate components, neither of which emit the same event as the other.
One thing you can try is disabling each components' attribute inheritance:
export default {
...
inheritAttrs: false
...
}
If this doesn't suit your needs, you could refactor the logic to handle both emitted events, i.e. rename the events to a shared name like "addOrDeleteResource", then determine which event is being emitted in App.vue and handle it accordingly.

How to store a value from another component's data?

I have two components, is there a way to store value from another component's data?
Here is Create.vue
<template>
<div id="main">
<Editor />
//some codes here
</div>
</template>
<script>
import Editor from './_Create_Editor.vue'
export default {
components: { Editor },
data: () => ({
text: ''
}),
}
</script>
And here is the _Create_Editor.vue.
<template>
//sample input for demonstration purposes
<input type="text" class="form-control" v-model="text"/>
</template>
The code above returns an error:
Property or method "text" is not defined on the instance but referenced during render
I want everytime I type the data: text from Create.vue has the value of it.
How can I possibly make this? Please help.
You can do this by using $emit.
Create.vue
<template>
<div id="main">
<Editor
#edit={onChangeText}
/>
//some codes here
</div>
</template>
<script>
import Editor from './_Create_Editor.vue'
export default {
components: { Editor },
data: () => ({
text: ''
}),
methods: {
onChangeText: function (value) {
this.text = value
}
}
}
</script>
_Create_Editor.vue
<template>
//sample input for demonstration purposes
<input
type="text"
class="form-control"
#change="onChange"
/>
</template>
<script>
export default {
methods: {
onChange: function (event) {
this.$emit('edit', event.target.value)
}
}
}
</script>

Data passed as undefined from child to parent component

I am making a file selection in the child component and once file is selected I want to pass the selected file to the parent component. I am not able to figure out how to do that. Please help out. If I try to get the print the value inside the onDocumentSelected(value) it comes out to be undefined.
Error message
Property or method "value" is not defined on the instance but referenced during render
Parent Component
<template>
<v-form :model='agency'>
<DocumentSelect
type="file"
ref="file"
:required="true"
name="vue-file-input"
#change="onDocumentSelected(value)"
/>
</v-form>
</template>
<script>
import DocumentSelect from 'views/document-selection.vue';
export default {
components: {
DocumentSelect
},
props: ['agency'],
methods: {
onDocumentSelected(value) {
console.log(value); //undefined
},
}
};
</script>
Child Component
<template>
<div class="input-group input-group--select primary--text" :class="{'input-group--required': required, 'input-group--error': hasError, 'error--text': hasError}" >
<div class="input-group__input">
<input
type="file"
name="name"
ref="file"
#change="onDocumentSelected" />
</div>
<div class="input-group__details">
<div class="input-group__messages input-group__error" v-for="error in errorBucket">
{{error}}
</div>
</div>
</div>
</template>
<script>
import Validatable from 'vuetify/es5/mixins/validatable.js'
export default {
mixins: [Validatable],
props: ['type', 'name', 'required'],
data: function () {
return {
inputValue: ''
};
},
watch: {
inputValue: function(value) {
this.validate();
console.log(value); // *Event {isTrusted: true, type: "change", target: input, currentTarget: null, eventPhase: 0, …}*
this.$emit('change', {value});
},
},
methods: {
onFileSelected(event) {
this.inputValue = event
},
},
};
</script>
Get rid of your watch method and move the logic inside onFileSelected:
#change="onFileSelected($event)"
onFileSelected(e) {
this.validate();
this.$emit('document-selected', e);
}
Then, in the parent, listen for the document-selected event:
<DocumentSelect
type="file"
ref="file"
:required="true"
name="vue-file-input"
#document-selected="onDocumentSelected($event)"
/>
You then have access to that value to do what you want with.

How to pass elements in a for loop to parent component?

Background I have a child component that loops through an array called "expenseButton" passed from my parent component. Within this for loop are elements that are getting updated. Specifically the "expense".
Child component
<form class="container">
<div class="buttonList" v-for="(expense, index) in expenseButton" :key="index">
<button type="button" #click="expenseButtonClick(expense)">{{expense.expensesKey}}</button>
<input class="textInput" v-model.number="expense.subExpense" type="number" />
</div>
</form>
<script>
export default {
props: {
expenseButton: Array,
},
methods: {
expenseButtonClick(expense) {
expense.expensesValue = expense.expensesValue - expense.subExpense;
}
}
}
</script>
Problem I understand that $emit events can pass data to the parent. However, I am trying to figure the best way to send the updated elements of the array back to the parent component.
The Parent component data
<template>
<expense-button :expenseButton="expenseButton"></expense-button>
</template>
<script>
export default {
components: {
"expense-button": Expenses
},
data() {
return {
expenseButton: [
{"expensesKey":"rent","expensesValue":null,"subExpense":""},
{"expensesKey":"movies","expensesValue":null,"subExpense":""},
{"expensesKey":"clothes","expensesValue":null,"subExpense":""}
],
};
}
}
</script>
I think you should use $emit.
Child component:
<form class="container">
<div class="buttonList" v-for="(expense, index) in expenseButton" :key="index">
<button type="button" #click="expenseButtonClick(expense)">{{expense.expensesKey}}</button>
<input class="textInput" v-model.number="expense.subExpense" type="number" />
</div>
</form>
<script>
export default {
props: {
expenseButton: Array,
},
methods: {
expenseButtonClick(expense) {
expense.expensesValue = expense.expensesValue - expense.subExpense;
this.$emit("expense-btn-clicked", expense)
}
}
}
</script>
Parent component:
<template>
<expense-button :expenseButton="expenseButton" #expense-btn-clicked="btnClickedHandler"></expense-button>
</template>
<script>
export default {
components: {
"expense-button": Expenses
},
data() {
return {
expenseButton: [
{"expensesKey":"rent","expensesValue":null,"subExpense":""},
{"expensesKey":"movies","expensesValue":null,"subExpense":""},
{"expensesKey":"clothes","expensesValue":null,"subExpense":""}
],
}
},
methods: {
btnClickedHandler(e) {
console.log(e)
}
}
}
</script>

Categories

Resources