Vue js passing HTML button name attribute as a PROPS - vue.js

I created a custom component which contains an HTML button tag, so I'm using this component many times as a shared component into a parent component. I would like to know if I can pass the name attribute from the HTML button tag as a prop, so I can have a dynamically HTML button tag name attribute.
<div class="toggle">
<button
class="btn"
name="ships">
</div>
<script>
export default {
props: {
ships: {
type: String,
required: true,
default: ''
}
}
</script>
<toggle
:ships="white"
/>
<toggle
:ships="grey"
/>
<toggle
:ships="black"
/>
CODE

I've updated your fiddle: https://codesandbox.io/s/00yxy5lqzn
Things I've changed:
Toogle.vue
<button class="btn" v-bind:name="ships">BUTTON </button>
To change an HTML attribute just add an v-bind: in front of it, because you can not use mustaches there.
App.vue
<div id="app">
<toggle ships="black" />
<toggle ships="grey" />
<toggle ships="white"/>
</div>
Removed the double dot -> now the content of the property will be interpreted as an String.
Edit: Alternative you could do it this way (result is the same): <toggle :ships="'black'" /> <-- it's probably the better way

You can do this without using a prop by using inheritAttrs.
export default {
inheritAttrs: false,
name: "toggle",
};
And then use $attrs to access any fallthrough attributes e.g. name.
<div class="toggle">
<button class="btn"
v-bind:name="$attrs.name">BUTTON </button>
</div>
And then using your component would just be
<div id="app">
<toggle name="black" />
<toggle name="grey" />
<toggle name="white"/>
</div>

Related

Why is v-model not working properly, returning'' Property "modelValue" was accessed during render but is not defined on instance.'' Vue 3

The Component I am making is a basic toggle switch made in vue using tailwind. during the initial render the switch is in an incorrect position, first click toggles the theme but the switch still stays the same, third click and forward the switch works properly
Switch.vue
<template>
<label class="switch relative inline-block w-[39px] h-[19px]">
<input type="checkbox" class="w-0 h-0 opacity-0" v-model="modelValue">
<span
class="absolute rounded-[34px] before:rounded-[50%] cursor-pointer top-0 left-0 right-0 bottom-0 bg-gray-300 transition shadow-inner before:absolute before:h-[17px] before:w-[17px] before:left-[1px] before:top-[1px] before:bg-white before:transition "
:class="[{
'before:translate-x-5 bg-blue-500': modelValue
}]" #click="$emit('update:modelValue', modelValue)"></span>
</label>
</template>
Parent.vue
// darkTheme comes from a pinia store.
<Switch v-model="darkTheme.enableDarkTheme" />
I was expecting the switch to work with v-model and toggle the theme, it works after a few clicks but first 3 clicks it does not toggle.
import { defineStore } from "pinia";
export let useThemeStore = defineStore('darkTheme', {
state: () => {
return {
enableDarkTheme: window.matchMedia('(prefers-color-scheme: dark)').matches,
}
},
actions: {
toggle() {
!this.enableDarkTheme;
}
}
})
Edit: Pinia seems to be sending the prop value as undefined on the first mutation, which seems to be causing the issue. please verify the store code
Referring to custom components v-model in the docs
https://vuejs.org/guide/components/v-model.html
for v-model in custom components props and emits need to be explicitly defined in the script setup, also see #Estus's comment about nested v-model
This is a simple vue component for a toggle slider
Switch.vue
<script setup>
defineProps(['modelValue'])
defineEmits(['update:modelValue'])
</script>
<template>
<label class="switch relative inline-block w-[39px] h-[19px]">
<input type="checkbox" class="w-0 h-0 opacity-0" :checked="modelValue">
<span
class="absolute rounded-[34px] before:rounded-[50%] cursor-pointer top-0 left-0 right-0 bottom-0 bg-gray-300 transition shadow-inner before:absolute before:h-[17px] before:w-[17px] before:left-[1px] before:top-[1px] before:bg-white before:transition "
:class="[{
'before:translate-x-5 bg-blue-500': modelValue
}]" #click="$emit('update:modelValue', !modelValue)"></span>
</label>
</template>
Parent Component
//Inside the parent component
<Switch v-model="darkTheme.enableDarkTheme" />

Dynamic Placeholder in Vue 3 with Global Component

I am trying to set dynamic text for the placeholder attribute on my search bar. Depending on the page, I want the text in the search bar to be different (I will define it in data()).
However, since the search bar component is a global component, it doesn't seem to be editable.
(As you see below is my try, I did it with v-model based on Vue docs, however when I try with placeholder it doesn't work...)
Snippet 1 - Search bar component
<template>
<!-- Search Componenet -->
<div class="mx-5 mb-3 form-group">
<br>
<input class="mb-5 form-control" type="search" :placeholder="placeholderValue" :value="modelValue" #load="$emit('update:placeholderValue', $event.target.value)" #input="$emit('update:modelValue', $event.target.value)" />
</div>
</template>
<script>
export default {
props: ['modelValue', 'placeholderValue'],
emits: ['update:modelValue', 'update:placeholderValue']
}
</script>
Snippet 2 - Album.vue
<template>
<div class="AlbumView">
<h1>{{header}}</h1>
<h2>{{header2}}</h2>
<br>
<!-- Search Componenet -->
<SearchComponent :placeholder="placeholderValue" v-model="searchQuery" />
<!-- Dynamic Song Route Button -->
<div class="button-container-all mx-5 pb-5">
<div v-for="item in datanew" :key="item.id">
{{ item.album }}
</div>
</div>
</div>
</template>
<script>
import { datatwo } from '#/data2'
export default {
data() {
return {
placeholderValue: "Search for Albums here...",
datanew: datatwo,
searchQuery: null,
header: "Browse by Album",
header2: "Select an Album:",
publicPath: process.env.BASE_URL
};
},
}
</script>
If this is possible?
If you want to do it with v-model (the Childcomponent changes the value of the placeholder) you have to use v-model:placeholder for it to work.
And also placeholderValue is not the way to go the "Value" at the end of a prop is only needed for modelValue which is the default v-model-binding (v-model="") but if you want named v-model-binding (v-model:placeholder="") you do not want to add the "Value" in the props and emits arrays.
Example:
usage of SearchComponent
<SearchComponent :placeholder="'placeholderValue'" v-model="searchQuery" />
instead of 'placeholderValue' you can put any string you want or variable. I just put the string 'placeholderValue' as an example.
SearchComponent
<template>
<!-- Search Componenet -->
<div class="mx-5 mb-3 form-group">
<br>
<input class="mb-5 form-control" type="search" :placeholder="placeholder" :value="modelValue" #load="$emit('update:placeholderValue', $event.target.value)" #input="$emit('update:modelValue', $event.target.value)" />
</div>
</template>
<script>
export default {
name: "SearchComponent",
props: ['modelValue', 'placeholder'],
emits: ['update:modelValue'],
}
</script>
<style scoped>
</style>

Passing v-model into a checkbox inside a Component in Vue 3?

I want to embed a checkbox inside a Vue3 Component and have the v-model binding passed down to the checkbox.
Inside the Component:
<!-- Tile.vue -->
<template>
<div>
<input type=checkbox v-model="$attrs">
</div>
</template>
<script>
export default {inheritAttrs: false}
</script>
Then in an outside file:
<template>
<Tile value="carrot" v-model="foods" />
<Tile value="tomatoes" v-model="foods" />
</template>
<script setup>
var foods = ref([]);
</script>
How do I achieve this?
The documentation says that v-model is just a shorthand for :modelValue and #update:modelValue but this is not universal as Vue obviously behaves differently for form elements such as smartly listening to onchange instead of oninput and modifying the property checked instead of value depending on the node.
If I use v-model on the outer component, how do I forward it to the checkbox and get the same smart behavior that Vue has?
I have found tons of controversial information. Some recommend using #input event (Vue 3 custom checkbox component with v-model and array of items). Some recommend emitting modelValue:update instead of update:modelValue (https://github.com/vuejs/core/issues/2667#issuecomment-732886315). Etc.. Following worked for me after hour of trial and error on latest Vuejs3
Child
<template>
<div class="form-check noselect">
<input class="form-check-input" type="checkbox" :id="id" :checked="modelValue" #change="$emit('update:modelValue', $event.target.checked)" />
<label class="form-check-label" :for="id"><slot /></label>
</div>
</template>
<script>
import { v4 as uuidv4 } from "uuid";
export default {
inheritAttrs: false,
emits: ["update:modelValue"],
props: {
modelValue: {
type: Boolean,
required: true,
},
},
setup() {
return {
id: uuidv4(),
};
},
};
</script>
Parent:
<Checkbox v-model="someVariable">Is true?</Checkbox>
you can verify that it works but doing this in parent:
var someVariable= ref(false);
watch(someVariable, () => {
console.log(someVariable.value);
});
p.s. The other solution above does not work for me. Author recommends using value property. But in example he passes v-model attribute. So I don't know exactly how it's supposed to work.
You can achieve the behavior by using emits to keep data in sync and behave as default v-model behavior. 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>
And in the parent component you can have as many checkboxes you want.
<template>
<div id="app">
<maincontent :showContent="showContent" />
<inputcheckbox text="one" v-model="checkedOne" />
<inputcheckbox text="two" v-model="checkedTwo" />
</div>
</template>
Here is a vue 2 example but is applicable to vue 3 as well. Hope this was helpful. Sandbox with this behavior:
https://codesandbox.io/embed/confident-buck-kith5?fontsize=14&hidenavigation=1&theme=dark

How to pass #blur into child component Vuejs

I created a custom Input component.
I needed pass #blur from vee-validate form to my custom input component.
It works great in normal html input tag. I no idea how could we pass the #blur into custom Input component.
Example 1 work correctly, it triggered the validation after blur the input.
<template>
<form #submit="onSubmit">
<input #blur="emailBlur" v-model="email" type="text" autocomplete="off" name="email" placeholder="email">
<button type="submit" :disabled="isSubmitting">Submit</button>
</form>
</template>
Example 2 with My custom Input Component:
// src/components/Input.vue
<template>
<div class="mt-2">
<label :for="name" class="h5">Name</label>
<input
:type="type"
:value="modelValue"
#change="$emit('update:modelValue', $event.target.value)"
:id="name"
:placeholder="placeholder"
/>
</div>
</template>
<script>
export default {
name: 'Input',
props: ["modelValue", 'name', 'type', 'placeholder'],
setup(props) {
console.log('props :>> ', props); // not receive the #blur
}
}
</script>
Parent Component (App.vue):
<template>
<form>
<Input #blur="emailBlur" v-model="email" type="text" name="email" placeholder="Custom input email" />
<button type="submit" :disabled="isSubmitting">Submit</button>
</form>
</template>
export default {
name: 'App',
components: {
Input
},
setup() {
// the vee validation values v-model to template
}
}
Sending the handler as props from the parent is not a good practice instead need to trigger the handler(present in the parent) from the child component. By doing so you will have an advantage where you can bind different blur handlers based on your requirement inside different parent components
To do so you can follow the below approach
Custom Input Component
// src/components/Input.vue
<template>
<div class="mt-2">
<label :for="name" class="h5">Name</label>
<input
:type="type"
:value="modelValue"
#change="$emit('update:modelValue', $event.target.value)"
:id="name"
:placeholder="placeholder"
#blur="$emit('blur')" //Change added
/>
</div>
</template>
<script>
export default {
name: 'Input',
props: ["modelValue", 'name', 'type', 'placeholder'],
emits: ['blur', 'update:modelValue'], // change added
}
</script>
Note:
for all v-models without arguments, make sure to change props and events name to modelValue and update:modelValue respectively
For Example:
Parent.vue
<ChildComponent v-model="pageTitle" />
and in Child.vue it should be like
export default {
props: {
modelValue: String // previously was `value: String`
},
emits: ['update:modelValue'],
methods: {
changePageTitle(title) {
this.$emit('update:modelValue', title) // previously was `this.$emit('input', title)`
}
}
}
What you are creating is usually called "transparent wrapper" component. What you want from this wrapper is to behave in almost every way as normal input component so the users of the component can work with it as it was normal input (but it is not)
In your case, you want to attach #blur event listener to your wrapper. But the problem is that blur is native browser event i.e. not a Vue event.
When you place event listener on a component for an event not specified in emits option (or v-bind an attribute that is not specified in component's props), Vue will treat it as Non-Prop Attribute. This means it take all such event listeners and non-prop attributes and place it on the root node of the component (div in your case)
But luckily there is a way to tell Vue "Hey, don't place those automatically on root, I know where to put it"
Use inheritAttrs: false option on your component
Put all non-prop attributes (including the event listeners) on the element you want - input in this case - using v-bind="$attrs"
Now you can even remove some props - for example placeholder (if you want), because if you use it directly on your component, Vue place it on input, which is what you want...
Also handling #change event is not optimal - you component allows to specify a type and different input types has different events. Nice trick around it is not to pass value and bind event explicitly, but instead use v-model with computed (see example below)
const app = Vue.createApp({
data() {
return {
text: ""
}
},
methods: {
onBlur() {
console.log("Blur!")
}
}
})
app.component('custom-input', {
inheritAttrs: false,
props: ["modelValue", 'name', 'type'],
emits: ['update:modelValue'],
computed: {
model: {
get() { return this.modelValue },
set(newValue) { this.$emit('update:modelValue', newValue) }
}
},
template: `
<div class="mt-2">
<label :for="name" class="h5">{{ name }}:</label>
<input
:type="type"
v-model="model"
:id="name"
v-bind="$attrs"
/>
</div>
`
})
app.mount("#app")
<script src="https://unpkg.com/vue#3.2.19/dist/vue.global.js"></script>
<div id='app'>
<custom-input type="text" name="email" v-model="text" placeholder="Type something..." #blur="onBlur"></custom-input>
<pre>{{ text }}</pre>
</div>

v-show not working with props

I am trying to hide or show button using props.
Here is the code
View (Blade)
<product-form-component savebutton="false" updatebutton="false"></product-form-component>
Component template
<template>
<div class="form-actions text-right col-md-12">
<button v-show="showsavebutton" class="btn btn-primary">Save</button>
<button v-show="updatemode && showupdatebutton" class="btn btn- primary">Update</button>
</div>
</template>
Javascript
export default {
props: ['showupdatebutton', 'showsavebutton', 'modalid']
}
Two points:
The props you are passing don't work the way you think they do; and
You have to create data variables (or props) in the component with the names you are using in the v-show.
Passing props
When you pass like:
<product-form-component savebutton="false" updatebutton="false"></product-form-component>
inside the component, the savebutton and updatebutton properties will be strings. In the example above, they won't be the boolean false, they will be the string "false".
To bind them to different values, use v-bind:propname or its shorthand :propname:
<product-form-component :savebutton="false" :updatebutton="false"></product-form-component>
That way, inside the component, those properties will really have the value false.
Variables inside component and v-show
The variables you use in the v-shows:
<button v-show="showsavebutton" ...
<button v-show="updatemode && showupdatebutton" ...
Don't exist in your component. You have to create data variables (or props) in the component with the names you are using in the v-show.
Considering you already have some props declared, here's an example of declaring those v-show variables in the data() using the props as initial value:
Vue.component('product-form-component', {
template: "#pfc",
props: ['updatebutton', 'savebutton', 'modalid'],
data() {
return {
updatemode: this.updatebutton, // initialized using props
showupdatebutton: this.updatebutton,
showsavebutton: this.savebutton
}
}
})
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
}
})
<script src="https://unpkg.com/vue"></script>
<template id="pfc">
<div class="form-actions text-right col-md-12">
<button v-show="showsavebutton" class="btn btn-primary">Save</button>
<button v-show="updatemode && showupdatebutton" class="btn btn- primary">Update</button>
</div>
</template>
<div id="app">
<p>{{ message }}</p>
<product-form-component :savebutton="true" :updatebutton="true"></product-form-component>
</div>
Props as passed down to child with the bind syntax :, so in your case you forgot to add it:
try:
<product-form-component :savebutton="false" :updatebutton="false"></product-form-component>